def find_center(img): h, w = img.shape roi_h = int(h * 2 / 3) roi_img = img[roi_h:, :] img_blur = cv2.GaussianBlur(roi_img, (15, 15), 0) # 高斯模糊 ret, th2 = cv2.threshold(img_blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) g2 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) open_img = cv2.morphologyEx(th2, cv2.MORPH_OPEN, g2, iterations=3) x_sum = np.sum(open_img, axis=0) x_point = np.where(x_sum > 0) point_x = int((x_point[0][0] + x_point[0][-1]) / 2) # print(roi_h, w) # np.savetxt('reshape_data.txt', x_point, delimiter=' ', fmt='%i') return point_x 转c++

时间: 2024-01-09 19:04:48 浏览: 26
#include <opencv2/opencv.hpp> using namespace cv; int find_center(Mat img) { int h = img.rows; int w = img.cols; int roi_h = h * 2 / 3; Mat roi_img = img(Rect(0, roi_h, w, h - roi_h)); Mat img_blur; GaussianBlur(roi_img, img_blur, Size(15, 15), 0); Mat th2; threshold(img_blur, th2, 0, 255, THRESH_BINARY+THRESH_OTSU); Mat g2 = getStructuringElement(MORPH_RECT, Size(3, 3)); Mat open_img; morphologyEx(th2, open_img, MORPH_OPEN, g2, Point(-1, -1), 3); Mat x_sum; reduce(open_img, x_sum, 0, REDUCE_SUM); std::vector<int> x_point; for (int i = 0; i < x_sum.cols; i++) { if (x_sum.at<uchar>(0, i) > 0) x_point.push_back(i); } int point_x = (x_point.front() + x_point.back()) / 2; return point_x; }

相关推荐

逐行详细解释以下代码并加注释from tensorflow import keras import matplotlib.pyplot as plt base_image_path = keras.utils.get_file( "coast.jpg", origin="https://img-datasets.s3.amazonaws.com/coast.jpg") plt.axis("off") plt.imshow(keras.utils.load_img(base_image_path)) #instantiating a model from tensorflow.keras.applications import inception_v3 model = inception_v3.InceptionV3(weights='imagenet',include_top=False) #配置各层对DeepDream损失的贡献 layer_settings = { "mixed4": 1.0, "mixed5": 1.5, "mixed6": 2.0, "mixed7": 2.5, } outputs_dict = dict( [ (layer.name, layer.output) for layer in [model.get_layer(name) for name in layer_settings.keys()] ] ) feature_extractor = keras.Model(inputs=model.inputs, outputs=outputs_dict) #定义损失函数 import tensorflow as tf def compute_loss(input_image): features = feature_extractor(input_image) loss = tf.zeros(shape=()) for name in features.keys(): coeff = layer_settings[name] activation = features[name] loss += coeff * tf.reduce_mean(tf.square(activation[:, 2:-2, 2:-2, :])) return loss #梯度上升过程 @tf.function def gradient_ascent_step(image, learning_rate): with tf.GradientTape() as tape: tape.watch(image) loss = compute_loss(image) grads = tape.gradient(loss, image) grads = tf.math.l2_normalize(grads) image += learning_rate * grads return loss, image def gradient_ascent_loop(image, iterations, learning_rate, max_loss=None): for i in range(iterations): loss, image = gradient_ascent_step(image, learning_rate) if max_loss is not None and loss > max_loss: break print(f"... Loss value at step {i}: {loss:.2f}") return image #hyperparameters step = 20. num_octave = 3 octave_scale = 1.4 iterations = 30 max_loss = 15. #图像处理方面 import numpy as np def preprocess_image(image_path): img = keras.utils.load_img(image_path) img = keras.utils.img_to_array(img) img = np.expand_dims(img, axis=0) img = keras.applications.inception_v3.preprocess_input(img) return img def deprocess_image(img): img = img.reshape((img.shape[1], img.shape[2], 3)) img /= 2.0 img += 0.5 img *= 255. img = np.clip(img, 0, 255).astype("uint8") return img #在多个连续 上运行梯度上升 original_img = preprocess_image(base_image_path) original_shape = original_img.shape[1:3] successive_shapes = [original_shape] for i in range(1, num_octave): shape = tuple([int(dim / (octave_scale ** i)) for dim in original_shape]) successive_shapes.append(shape) successive_shapes = successive_shapes[::-1] shrunk_original_img = tf.image.resize(original_img, successive_shapes[0]) img = tf.identity(original_img) for i, shape in enumerate(successive_shapes): print(f"Processing octave {i} with shape {shape}") img = tf.image.resize(img, shape) img = gradient_ascent_loop( img, iterations=iterations, learning_rate=step, max_loss=max_loss ) upscaled_shrunk_original_img = tf.image.resize(shrunk_original_img, shape) same_size_original = tf.image.resize(original_img, shape) lost_detail = same_size_original - upscaled_shrunk_original_img img += lost_detail shrunk_original_img = tf.image.resize(original_img, shape) keras.utils.save_img("DeepDream.png", deprocess_image(img.numpy()))

def get_Image_dim_len(png_dir: str,jpg_dir:str): png = Image.open(png_dir) png_w,png_h=png.width,png.height #若第十行报错,说明jpg图片没有对应的png图片 png_dim_len = len(np.array(png).shape) assert png_dim_len==2,"提示:存在三维掩码图" jpg=Image.open(jpg_dir) jpg = ImageOps.exif_transpose(jpg) jpg.save(jpg_dir) jpg_w,jpg_h=jpg.width,jpg.height print(jpg_w,jpg_h,png_w,png_h) assert png_w==jpg_w and png_h==jpg_h,print("提示:%s mask图与原图宽高参数不一致"%(png_dir)) """2.读取单个图像均值和方差""" def pixel_operation(image_path: str): img = cv.imread(image_path, cv.IMREAD_COLOR) means, dev = cv.meanStdDev(img) return means,dev """3.分割数据集,生成label文件""" # 原始数据集 ann上一级 data_root = './work/voc_data02' #图像地址 image_dir="./JPEGImages" # ann图像文件夹 ann_dir = "./SegmentationClass" # txt文件保存路径 split_dir = './ImageSets/Segmentation' mmengine.mkdir_or_exist(osp.join(data_root, split_dir)) png_filename_list = [osp.splitext(filename)[0] for filename in mmengine.scandir( osp.join(data_root, ann_dir), suffix='.png')] jpg_filename_list=[osp.splitext(filename)[0] for filename in mmengine.scandir( osp.join(data_root, image_dir), suffix='.jpg')] assert len(jpg_filename_list)==len(png_filename_list),"提示:原图与掩码图数量不统一" print("数量检查无误") for i in range(10): random.shuffle(jpg_filename_list) red_num=0 black_num=0 with open(osp.join(data_root, split_dir, 'trainval.txt'), 'w+') as f: length = int(len(jpg_filename_list)) for line in jpg_filename_list[:length]: pngpath=osp.join(data_root,ann_dir,line+'.bmp') jpgpath=osp.join(data_root,image_dir,line+'.bmp') get_Image_dim_len(pngpath,jpgpath) img=cv.imread(pngpath,cv.IMREAD_GRAYSCALE) red_num+=len(img)*len(img[0])-len(img[img==0]) black_num+=len(img[img==0]) f.writelines(line + '\n') value=0 train_mean,train_dev=[[0.0,0.0,0.0]],[[0.0,0.0,0.0]] with open(osp.join(data_root, split_dir, 'train.txt'), 'w+') as f: train_length = int(len(jpg_filename_list) * 7/ 10) for line in jpg_filename_list[:train_length]: jpgpath=osp.join(data_root,image_dir,line+'.bmp') mean,dev=pixel_operation(jpgpath) train_mean+=mean train_dev+=dev f.writelines(line + '\n') with open(osp.join(data_root, split_dir, 'val.txt'), 'w+') as f: for line in jpg_filename_list[train_length:]: jpgpath=osp.join(data_root,image_dir,line+'.bmp') mean,dev=pixel_operation(jpgpath) train_mean+=mean train_dev+=dev f.writelines(line + '\n') 帮我把这段代码改成bmp图像可以制作数据集的代码

def save_kitti_format(sample_id, calib, bbox3d, kitti_output_dir, scores, img_shape): corners3d = kitti_utils.boxes3d_to_corners3d(bbox3d) img_boxes, _ = calib.corners3d_to_img_boxes(角3d) img_boxes[:, 0] = np.clip(img_boxes[:, 0], 0, img_shape[1] - 1) img_boxes[:, 1] = np.clip(img_boxes[:, 1], 0, img_shape[0] - 1) img_boxes[:, 2] = np.clip(img_boxes[:, 2], 0, img_shape[1] - 1) img_boxes[:, 3] = np.clip(img_boxes[:, 3], 0, img_shape[0] - 1) img_boxes_w = img_boxes[:, 2] - img_boxes[:, 0] img_boxes_h = img_boxes[:, 3] - img_boxes[:, 1] box_valid_mask = np.logical_and(img_boxes_w < img_shape[1] * 0.8, img_boxes_h < img_shape[0] * 0.8) kitti_output_file = os.path.join(kitti_output_dir, '%06d.txt' % sample_id) with open(kitti_output_file, 'w') as f: for k in range(bbox3d.shape[0]): if box_valid_mask[k] == 0: continue x, z, ry = bbox3d[k, 0], bbox3d[k, 2], bbox3d[k, 6] beta = np.arctan2(z, x) alpha = -np.sign(beta) * np.pi / 2 + beta + ry print('%s -1 -1 %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f' % (cfg.CLASSES, alpha, img_boxes[k, 0], img_boxes[k, 1], img_boxes[k, 2], img_boxes[k, 3], bbox3d[k, 3], bbox3d[k, 4], bbox3d[k, 5], bbox3d[k, 0], bbox3d[k, 1], bbox3d[k, 2], bbox3d[k, 6], scores[k]), file=f)解释这段代码,并且根据已知的条件,已知sample_id, 点云的检测结果(x, y, z, w, h, l, yaw), kitti_output_dir, scores, img_shape,calib文件的路径且格式与 KITTI 数据集的标定文件格式相同,要求得到2D检测框的坐标,和alpha,仿写出Python函数,并给出示例

最新推荐

recommend-type

node-v6.11.1-linux-ppc64le.tar.xz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

ArduinoESP32板卡支持包

ArduinoESP32板卡支持包
recommend-type

Inno-Tasks-Test.zip

无需在自定义页面中使用复杂的设置,而是使用Inno设置[Task]使安装更简单。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

机器学习怎么将excel转为csv文件

机器学习是一种利用计算机算法和统计数据的方法来训练计算机来进行自动学习的科学,无法直接将excel文件转为csv文件。但是可以使用Python编程语言来读取Excel文件内容并将其保存为CSV文件。您可以使用Pandas库来读取Excel文件,并使用to_csv()函数将其保存为CSV格式。以下是代码示例: ```python import pandas as pd # 读取 Excel 文件 excel_data = pd.read_excel('example.xlsx') # 将数据保存为 CSV 文件 excel_data.to_csv('example.csv', index=
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这