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++ opencv如何实现

时间: 2023-12-10 12:03:47 浏览: 32
以下是 C++ OpenCV 实现 find_center 函数的代码: ```c++ #include <iostream> #include <opencv2/opencv.hpp> using namespace std; 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 = Mat::zeros(1, w, CV_32F); reduce(open_img, x_sum, 0, REDUCE_SUM, CV_32F); int nonzero_count = countNonZero(x_sum); if (nonzero_count == 0) { return -1; } int nonzero_start = 0; int nonzero_end = w - 1; for (int i = 0; i < w; i++) { if (x_sum.at<float>(0, i) > 0) { nonzero_start = i; break; } } for (int i = w - 1; i >= 0; i--) { if (x_sum.at<float>(0, i) > 0) { nonzero_end = i; break; } } int point_x = (nonzero_start + nonzero_end) / 2; return point_x; } int main() { Mat img = imread("test.jpg", IMREAD_GRAYSCALE); int center = find_center(img); cout << "Center point x-coordinate: " << center << endl; return 0; } ``` 需要注意的是,在 C++ 中,OpenCV 中的函数名和参数可能会略有不同,需要根据情况进行调整。

相关推荐

逐行详细解释以下代码并加注释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

简历模板-前端开发简历模板

简历模板
recommend-type

计算机专业毕业设计范例424篇jsp17529零食小吃食品购物销售网站 ssh mysql 录像.rar

博主给大家详细整理了计算机毕业设计最新项目,对项目有任何疑问(部署跟文档),都可以问博主哦~ 一、JavaWeb管理系统毕设项目【计算机毕设选题】计算机毕业设计选题,500个热门选题推荐,更多作品展示 计算机毕业设计|PHP毕业设计|JSP毕业程序设计|Android毕业设计|Python设计论文|微信小程序设计
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

MySQL数据库性能提升秘籍:揭秘性能下降幕后真凶及解决策略

![MySQL数据库性能提升秘籍:揭秘性能下降幕后真凶及解决策略](http://xiaoyuge.work/explain-sql/index/2.png) # 1. MySQL数据库性能优化概述** MySQL数据库性能优化是一项至关重要的任务,可以显著提高应用程序的响应时间和整体用户体验。优化涉及识别和解决影响数据库性能的因素,包括硬件资源瓶颈、软件配置不当和数据库设计缺陷。通过采取适当的优化策略,可以显著提升数据库性能,满足业务需求并提高用户满意度。 # 2. MySQL数据库性能下降的幕后真凶 ### 2.1 硬件资源瓶颈 #### 2.1.1 CPU利用率过高 **症状:
recommend-type

如何在unity创建按钮

在 Unity 中创建按钮的步骤如下: 1. 在 Unity 中创建一个 UI Canvas,选择 GameObject -> UI -> Canvas。 2. 在 Canvas 中创建一个按钮,选择 GameObject -> UI -> Button。 3. 在场景视图中调整按钮的位置和大小。 4. 在 Inspector 中设置按钮的文本、颜色、字体等属性。 5. 添加按钮的响应事件,选择按钮,在 Inspector 的 On Click () 中添加相应的方法。 这样就可以创建一个按钮了,你可以在游戏中使用它来触发相应的操作。
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

表锁问题全解析,深度解读MySQL表锁问题及解决方案

![表锁问题全解析,深度解读MySQL表锁问题及解决方案](https://img-blog.csdnimg.cn/img_convert/a89711a10f6b856a777a9eed389c5112.png) # 1. 表锁基础** 表锁是一种数据库并发控制机制,用于防止多个事务同时访问和修改同一行或表中的数据,从而保证数据的完整性和一致性。表锁通过对表或表中的特定行施加锁来实现,以确保在事务完成之前,其他事务不能对这些数据进行修改。 表锁分为两种主要类型:共享锁(S锁)和排他锁(X锁)。共享锁允许多个事务同时读取同一行或表中的数据,但不能修改。排他锁则允许一个事务独占地访问和修改同
recommend-type

电脑上怎么获取文件路径

在 Windows 操作系统中,你可以按住 Shift 键并右键单击文件或文件夹,然后选择“复制为路径”选项,该选项会将文件或文件夹的路径复制到剪贴板中。你也可以直接打开文件或文件夹所在的目录,然后在地址栏中复制路径。在 Mac 操作系统中,你可以在 Finder 中选中文件或文件夹,然后从菜单栏中选择“文件”->“获取信息”,在弹出的窗口中可以找到文件或文件夹的路径。