import cv2 import numpy as np def cv_show(name,img): cv2.imshow(name,img) cv2.waitKey() cv2.destroyAllWindows() def get_img(path1,path2): img1 = cv2.imread(path1) img2 = cv2.imread(path2) #原图像变换为灰度图 img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) return img1,img2,img1_gray,img2_gray def get_info(img1_gray,img2_gray): # 尺度不变特征变换 sift = cv2.SIFT_create() # 关键点以及特征向量计算 kp1, des1 = sift.detectAndCompute(img1_gray, None) kp2, des2 = sift.detectAndCompute(img2_gray, None) kp1 = np.float32([kp.pt for kp in kp1]) kp2 = np.float32([kp.pt for kp in kp2]) return kp1,des1,kp2,des2 def get_match(kp1,kp2,des1,des2): # 特征点交叉检验 bf = cv2.BFMatcher() matches = bf.knnMatch(des1, des2,k=2) idx_pair=[] for m,n in matches: if m.distance<n.distance*0.75: idx_pair.append((m.queryIdx,m.trainIdx)) if len(idx_pair)>4: pt_list1 = np.float32([kp1[i] for (i, _) in idx_pair]) pt_list2 = np.float32([kp1[i] for (_, i) in idx_pair]) H,_ = cv2.findHomography(pt_list2,pt_list1,cv2.RANSAC,4) result = cv2.warpPerspective(img2, H, (img1.shape[1] + img2.shape[1], img1.shape[0])) result[0:img1.shape[0], 0:img1.shape[1]] = img1 return result #main函数 path1='img1.jpg' path2='img2.jpg' img1,img2,img1_gray,img2_gray=get_img(path1,path2) kp1,des1,kp2,des2=get_info(img1_gray,img2_gray) result=get_match(kp1,des1,kp2,des2) cv_show('result',result)

时间: 2024-04-01 16:34:16 浏览: 13
这段代码是一个基于SIFT特征点匹配的图像拼接代码。代码中先读取了两张图片,然后将其转换为灰度图像,并利用SIFT算法提取各自的关键点和特征向量,之后利用BFMatcher进行特征点匹配,再进行交叉检验,得到匹配点对,进而利用findHomography计算出变换矩阵H,最后利用warpPerspective函数将图像2变换到图像1的位置,并将两幅图像拼接在一起。最后使用cv_show函数显示拼接后的图像。 需要注意的是,SIFT算法是一种有专利的算法,如果使用OpenCV 3.4.2及以后的版本,需要安装opencv-contrib-python才能使用SIFT算法。如果没有安装该库,可以使用SURF算法代替SIFT算法进行特征提取。同时,该代码还存在一些问题,比如在利用findHomography计算变换矩阵时,应该将pt_list2放在前面,pt_list1放在后面,否则会导致拼接的结果不正确。此外,在利用warpPerspective函数变换图像时,应该先将变换矩阵H取反,否则得到的结果也会不正确。
相关问题

import cv2 import numpy as np def cv_show(name,img): cv2.imshow(name,img) cv2.waitKey() cv2.destroyAllWindows() def get_img(path1,path2): img1 = cv2.imread(path1) img2 = cv2.imread(path2) img1 = cv2.resize(img1, (300, 400)) img2 = cv2.resize(img2, (300, 400)) #原图像变换为灰度图 img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) return img1,img2,img1_gray,img2_gray def get_info(img1_gray,img2_gray): # 尺度不变特征变换 sift = cv2.SIFT_create() # 关键点以及特征向量计算 kp1, des1 = sift.detectAndCompute(img1_gray, None) kp2, des2 = sift.detectAndCompute(img2_gray, None) kp1 = np.float32([kp.pt for kp in kp1]) kp2 = np.float32([kp.pt for kp in kp2]) return kp1,des1,kp2,des2 def get_match(kp1,kp2,des1,des2): # 特征点交叉检验 bf = cv2.BFMatcher() matches = bf.knnMatch(des1, des2,k=2) idx_pair=[] for m,n in matches: if m.distance<n.distance*0.75: idx_pair.append((m.queryIdx,m.trainIdx)) if len(idx_pair)>4: pt_list1 = np.float32([kp1[i] for (i, _) in idx_pair]) pt_list2 = np.float32([kp1[i] for (_, i) in idx_pair]) H,_ = cv2.findHomography(pt_list2,pt_list1,cv.RANSAC,4) result = cv2.warpPerspective(img2, H, (img1.shape[1] + img2.shape[1], img1.shape[0])) result[0:img1.shape[0], 0:img1.shape[1]] = img1 return result #main函数 path1='img1.jpg' path2='img2.jpg' img1,img2,img1_gray,img2_gray=get_img(path1,path2) kp1,des1,kp2,des2=get_info(img1_gray,img2_gray) result=get_match(kp1,des1,kp2,des2) cv_show('result',result)对以上代码debug

这段代码的功能是将两张图片进行拼接,其中使用了SIFT算法进行特征点提取和匹配,以及RANSAC算法计算单应性矩阵。对于代码本身,我看到以下几个问题: 1.第一行的import语句应该写在不同的行中,而不是在同一行中。 2.在函数get_match()中,第12行的cv.RANSAC应该改为cv2.RANSAC。 3.在函数get_match()中,第20行的kp1应该改为kp2。 4.在函数get_match()中,第22行的img2应该改为img1。 5.在主函数中,img1和img2的大小应该保持一致,否则无法进行拼接。 6.在主函数中,应该调用cv_show()函数来显示img1和img2,以便查看它们的内容。 7.在主函数中,应该将result保存为文件,而不是直接展示在屏幕上。 希望我的解答能够帮助到你!

修改此代码使其可重复运行import pygame import sys from pygame.locals import * from robomaster import * import cv2 import numpy as np focal_length = 750 # 焦距 known_radius = 2 # 已知球的半径 def calculate_distance(focal_length, known_radius, perceived_radius): distance = (known_radius * focal_length) / perceived_radius return distance def show_video(ep_robot, screen): 获取机器人第一视角图像帧 img = ep_robot.camera.read_cv2_image(strategy="newest") 转换图像格式,转换为pygame的surface对象 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.transpose(img) # 行列互换 img = pygame.surfarray.make_surface(img) screen.blit(img, (0, 0)) # 绘制图像 def detect_white_circle(ep_robot): 获取机器人第一视角图像帧 img = ep_robot.camera.read_cv2_image(strategy="newest") 转换为灰度图像 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 进行中值滤波处理 gray = cv2.medianBlur(gray, 5) 检测圆形轮廓 circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 50, param1=160, param2=40, minRadius=5, maxRadius=60) if circles is not None: circles = np.uint16(np.around(circles)) for circle in circles[0, :]: center = (circle[0], circle[1]) known_radius = circle 在图像上绘制圆形轮廓 cv2.circle(img, center, known_radius, (0, 255, 0), 2) 显示图像 distance = calculate_distance(focal_length, known_radius, known_radius) 在图像上绘制圆和距离 cv2.circle(img, center, known_radius, (0, 255, 0), 2) cv2.putText(img, f"Distance: {distance:.2f} cm", (center[0] - known_radius, center[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.imshow("White Circle Detection", img) cv2.waitKey(1) def main(): pygame.init() screen_size = width, height = 1280, 720 screen = pygame.display.set_mode(screen_size) ep_robot = robot.Robot() ep_robot.initialize(conn_type='ap') version = ep_robot.get_version() print("Robot version: {0}".format(version)) ep_robot.camera.start_video_stream(display=False) pygame.time.wait(100) clock = pygame.time.Clock() while True: clock.tick(5) # 将帧数设置为25帧 for event in pygame.event.get(): if event.type == QUIT: ep_robot.close() pygame.quit() sys.exit() show_video(ep_robot, screen) detect_white_circle(ep_robot) if name == 'main': main()

修改后的代码如下所示: ```python import pygame import sys from pygame.locals import * from robomaster import robot import cv2 import numpy as np focal_length = 750 # 焦距 known_radius = 2 # 已知球的半径 def calculate_distance(focal_length, known_radius, perceived_radius): distance = (known_radius * focal_length) / perceived_radius return distance def show_video(ep_robot, screen): # 获取机器人第一视角图像帧 img = ep_robot.camera.read_cv2_image(strategy="newest") # 转换图像格式,转换为pygame的surface对象 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.transpose(img) # 行列互换 img = pygame.surfarray.make_surface(img) screen.blit(img, (0, 0)) # 绘制图像 def detect_white_circle(ep_robot): # 获取机器人第一视角图像帧 img = ep_robot.camera.read_cv2_image(strategy="newest") # 转换为灰度图像 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 进行中值滤波处理 gray = cv2.medianBlur(gray, 5) # 检测圆形轮廓 circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 50, param1=160, param2=40, minRadius=5, maxRadius=60) if circles is not None: circles = np.uint16(np.around(circles)) for circle in circles[0, :]: center = (circle[0], circle[1]) known_radius = circle[2] # 在图像上绘制圆形轮廓 cv2.circle(img, center, known_radius, (0, 255, 0), 2) # 计算距离 distance = calculate_distance(focal_length, known_radius, known_radius) # 在图像上绘制圆和距离 cv2.circle(img, center, known_radius, (0, 255, 0), 2) cv2.putText(img, f"Distance: {distance:.2f} cm", (center[0] - known_radius, center[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.imshow("White Circle Detection", img) cv2.waitKey(1) def main(): pygame.init() screen_size = width, height = 1280, 720 screen = pygame.display.set_mode(screen_size) ep_robot = robot.Robot() ep_robot.initialize(conn_type='ap') version = ep_robot.get_version() print("Robot version: {0}".format(version)) ep_robot.camera.start_video_stream(display=False) pygame.time.wait(100) clock = pygame.time.Clock() while True: clock.tick(5) # 将帧数设置为25帧 for event in pygame.event.get(): if event.type == QUIT: ep_robot.close() pygame.quit() sys.exit() show_video(ep_robot, screen) detect_white_circle(ep_robot) if __name__ == '__main__': main() ```

相关推荐

import numpy as np import cv2 class ColorMeter(object): color_hsv = { # HSV,H表示色调(度数表示0-180),S表示饱和度(取值0-255),V表示亮度(取值0-255) # "orange": [np.array([11, 115, 70]), np.array([25, 255, 245])], "yellow": [np.array([11, 115, 70]), np.array([34, 255, 245])], "green": [np.array([35, 115, 70]), np.array([77, 255, 245])], "lightblue": [np.array([78, 115, 70]), np.array([99, 255, 245])], "blue": [np.array([100, 115, 70]), np.array([124, 255, 245])], "purple": [np.array([125, 115, 70]), np.array([155, 255, 245])], "red": [np.array([156, 115, 70]), np.array([179, 255, 245])], } def __init__(self, is_show=False): self.is_show = is_show self.img_shape = None def detect_color(self, frame): self.img_shape = frame.shape res = {} # 将图像转化为HSV格式 hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) for text, range_ in self.color_hsv.items(): # 去除颜色范围外的其余颜色 mask = cv2.inRange(hsv, range_[0], range_[1]) erosion = cv2.erode(mask, np.ones((1, 1), np.uint8), iterations=2) dilation = cv2.dilate(erosion, np.ones((1, 1), np.uint8), iterations=2) target = cv2.bitwise_and(frame, frame, mask=dilation) # 将滤波后的图像变成二值图像放在binary中 ret, binary = cv2.threshold(dilation, 127, 255, cv2.THRESH_BINARY) # 在binary中发现轮廓,轮廓按照面积从小到大排列 contours, hierarchy = cv2.findContours( binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) if len(contours) > 0: # cv2.boundingRect()返回轮廓矩阵的坐标值,四个值为x, y, w, h, 其中x, y为左上角坐标,w,h为矩阵的宽和高 boxes = [ box for box in [cv2.boundingRect(c) for c in contours] if min(frame.shape[0], frame.shape[1]) / 10 < min(box[2], box[3]) < min(frame.shape[0], frame.shape[1]) / 1 ] if boxes: res[text] = boxes if self.is_show: for box in boxes: x, y, w, h = box # 绘制矩形框对轮廓进行定位 cv2.rectangle( frame, (x, y), (x + w, y + h), (153, 153, 0), 2 ) # 将绘制的图像保存并展示 # cv2.imwrite(save_image, img) cv2.putText( frame, # image text, # text (x, y), # literal direction cv2.FONT_HERSHEY_SIMPLEX, # dot font 0.9, # scale (255, 255, 0), # color 2, # border ) if self.is_show: cv2.imshow("image", frame) cv2.waitKey(1) # cv2.destroyAllWindows() return res if __name__ == "__main__": cap = cv2.VideoCapture(0) m = ColorMeter(is_show=True) while True: success, frame = cap.read() res = m.detect_color(frame) print(res) if cv2.waitKey(1) & 0xFF == ord('q'): break

最新推荐

recommend-type

图像处理案例一 信用卡数字识别

def cv_show(name,img): cv.imshow(name,img) cv.waitKey(0) cv.destroyAllWindows() # 先处理template tempalte_img = cv.imread("E:/opencv/picture/ocr_a_reference.png") tempalte_gray = cv....
recommend-type

图像处理案列三之图像拼接

import cv2 as cv import numpy as np def cv_show(name,img): cv.imshow(name,img) cv.waitKey(0) cv.destroyAllWindows() def detectAndDescribe(image): gray = cv.cvtColor(image,cv.COLOR_BGR2...
recommend-type

微信小程序-番茄时钟源码

微信小程序番茄时钟的源码,支持进一步的修改。番茄钟,指的是把工作任务分解成半小时左右,集中精力工作25分钟后休息5分钟,如此视作种一个“番茄”,而“番茄工作法”的流程能使下一个30分钟更有动力。
recommend-type

激光雷达专题研究:迈向高阶智能化关键,前瞻布局把握行业脉搏.pdf

电子元件 电子行业 行业分析 数据分析 数据报告 行业报告
recommend-type

安享智慧理财测试项目Mock服务代码

安享智慧理财测试项目Mock服务代码
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

解释minorization-maximization (MM) algorithm,并给出matlab代码编写的例子

Minorization-maximization (MM) algorithm是一种常用的优化算法,用于求解非凸问题或含有约束的优化问题。该算法的基本思想是通过构造一个凸下界函数来逼近原问题,然后通过求解凸下界函数的最优解来逼近原问题的最优解。具体步骤如下: 1. 初始化参数 $\theta_0$,设 $k=0$; 2. 构造一个凸下界函数 $Q(\theta|\theta_k)$,使其满足 $Q(\theta_k|\theta_k)=f(\theta_k)$; 3. 求解 $Q(\theta|\theta_k)$ 的最优值 $\theta_{k+1}=\arg\min_\theta Q(
recommend-type

JSBSim Reference Manual

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