Python OpenCV实现鼠标画框

分手后的思念是犯贱 2022-03-16 14:58 571阅读 0赞

Python OpenCV实现鼠标画框

使用Python+OpenCV实现鼠标画框的代码:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9wYW5qaW5xdWFuLmJsb2cuY3Nkbi5uZXQ_size_16_color_FFFFFF_t_70

  1. # -*-coding: utf-8 -*-
  2. """
  3. @Project: IntelligentManufacture
  4. @File : user_interaction.py
  5. @Author : panjq
  6. @E-mail : pan_jinquan@163.com
  7. @Date : 2019-02-21 15:03:18
  8. """
  9. # -*- coding: utf-8 -*-
  10. import cv2
  11. from utils import image_processing
  12. import numpy as np
  13. global img
  14. global point1, point2
  15. global g_rect
  16. def on_mouse(event, x, y, flags, param):
  17. global img, point1, point2,g_rect
  18. img2 = img.copy()
  19. if event == cv2.EVENT_LBUTTONDOWN: # 左键点击,则在原图打点
  20. print("1-EVENT_LBUTTONDOWN")
  21. point1 = (x, y)
  22. cv2.circle(img2, point1, 10, (0, 255, 0), 5)
  23. cv2.imshow('image', img2)
  24. elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): # 按住左键拖曳,画框
  25. print("2-EVENT_FLAG_LBUTTON")
  26. cv2.rectangle(img2, point1, (x, y), (255, 0, 0), thickness=2)
  27. cv2.imshow('image', img2)
  28. elif event == cv2.EVENT_LBUTTONUP: # 左键释放,显示
  29. print("3-EVENT_LBUTTONUP")
  30. point2 = (x, y)
  31. cv2.rectangle(img2, point1, point2, (0, 0, 255), thickness=2)
  32. cv2.imshow('image', img2)
  33. if point1!=point2:
  34. min_x = min(point1[0], point2[0])
  35. min_y = min(point1[1], point2[1])
  36. width = abs(point1[0] - point2[0])
  37. height = abs(point1[1] - point2[1])
  38. g_rect=[min_x,min_y,width,height]
  39. cut_img = img[min_y:min_y + height, min_x:min_x + width]
  40. cv2.imshow('ROI', cut_img)
  41. def get_image_roi(rgb_image):
  42. '''
  43. 获得用户ROI区域的rect=[x,y,w,h]
  44. :param rgb_image:
  45. :return:
  46. '''
  47. bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
  48. global img
  49. img=bgr_image
  50. cv2.namedWindow('image')
  51. while True:
  52. cv2.setMouseCallback('image', on_mouse)
  53. # cv2.startWindowThread() # 加在这个位置
  54. cv2.imshow('image', img)
  55. key=cv2.waitKey(0)
  56. if key==13 or key==32:#按空格和回车键退出
  57. break
  58. cv2.destroyAllWindows()
  59. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  60. return g_rect
  61. def select_user_roi(image_path):
  62. '''
  63. 由于原图的分辨率较大,这里缩小后获取ROI,返回时需要重新scale对应原图
  64. :param image_path:
  65. :return:
  66. '''
  67. orig_image = image_processing.read_image(image_path)
  68. orig_shape = np.shape(orig_image)
  69. resize_image = image_processing.resize_image(orig_image, resize_height=800,resize_width=None)
  70. re_shape = np.shape(resize_image)
  71. g_rect=get_image_roi(resize_image)
  72. orgi_rect = image_processing.scale_rect(g_rect, re_shape,orig_shape)
  73. roi_image=image_processing.get_rect_image(orig_image,orgi_rect)
  74. image_processing.cv_show_image("RECT",roi_image)
  75. image_processing.show_image_rect("image",orig_image,orgi_rect)
  76. return orgi_rect
  77. if __name__ == '__main__':
  78. # image_path="../dataset/images/IMG_0007.JPG"
  79. image_path="../dataset/test_images/lena.jpg"
  80. # rect=get_image_roi(image)
  81. rect=select_user_roi(image_path)
  82. print(rect)

其中image_processing.py文件如下:

  1. # -*-coding: utf-8 -*-
  2. """
  3. @Project: IntelligentManufacture
  4. @File : image_processing.py
  5. @Author : panjq
  6. @E-mail : pan_jinquan@163.com
  7. @Date : 2019-02-14 15:34:50
  8. """
  9. import os
  10. import glob
  11. import cv2
  12. import numpy as np
  13. import matplotlib.pyplot as plt
  14. def show_image(title, image):
  15. '''
  16. 调用matplotlib显示RGB图片
  17. :param title: 图像标题
  18. :param image: 图像的数据
  19. :return:
  20. '''
  21. # plt.figure("show_image")
  22. # print(image.dtype)
  23. plt.imshow(image)
  24. plt.axis('on') # 关掉坐标轴为 off
  25. plt.title(title) # 图像题目
  26. plt.show()
  27. def cv_show_image(title, image):
  28. '''
  29. 调用OpenCV显示RGB图片
  30. :param title: 图像标题
  31. :param image: 输入RGB图像
  32. :return:
  33. '''
  34. channels=image.shape[-1]
  35. if channels==3:
  36. image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # 将BGR转为RGB
  37. cv2.imshow(title,image)
  38. cv2.waitKey(0)
  39. def read_image(filename, resize_height=None, resize_width=None, normalization=False):
  40. '''
  41. 读取图片数据,默认返回的是uint8,[0,255]
  42. :param filename:
  43. :param resize_height:
  44. :param resize_width:
  45. :param normalization:是否归一化到[0.,1.0]
  46. :return: 返回的RGB图片数据
  47. '''
  48. bgr_image = cv2.imread(filename)
  49. # bgr_image = cv2.imread(filename,cv2.IMREAD_IGNORE_ORIENTATION|cv2.IMREAD_COLOR)
  50. if bgr_image is None:
  51. print("Warning:不存在:{}", filename)
  52. return None
  53. if len(bgr_image.shape) == 2: # 若是灰度图则转为三通道
  54. print("Warning:gray image", filename)
  55. bgr_image = cv2.cvtColor(bgr_image, cv2.COLOR_GRAY2BGR)
  56. rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB) # 将BGR转为RGB
  57. # show_image(filename,rgb_image)
  58. # rgb_image=Image.open(filename)
  59. rgb_image = resize_image(rgb_image,resize_height,resize_width)
  60. rgb_image = np.asanyarray(rgb_image)
  61. if normalization:
  62. # 不能写成:rgb_image=rgb_image/255
  63. rgb_image = rgb_image / 255.0
  64. # show_image("src resize image",image)
  65. return rgb_image
  66. def resize_image(image,resize_height, resize_width):
  67. '''
  68. :param image:
  69. :param resize_height:
  70. :param resize_width:
  71. :return:
  72. '''
  73. image_shape=np.shape(image)
  74. height=image_shape[0]
  75. width=image_shape[1]
  76. if (resize_height is None) and (resize_width is None):#错误写法:resize_height and resize_width is None
  77. return image
  78. if resize_height is None:
  79. resize_height=int(height*resize_width/width)
  80. elif resize_width is None:
  81. resize_width=int(width*resize_height/height)
  82. image = cv2.resize(image, dsize=(resize_width, resize_height))
  83. return image
  84. def scale_image(image,scale):
  85. '''
  86. :param image:
  87. :param scale: (scale_w,scale_h)
  88. :return:
  89. '''
  90. image = cv2.resize(image,dsize=None, fx=scale[0],fy=scale[1])
  91. return image
  92. def get_rect_image(image,rect):
  93. '''
  94. :param image:
  95. :param rect: [x,y,w,h]
  96. :return:
  97. '''
  98. x, y, w, h=rect
  99. cut_img = image[y:(y+ h),x:(x+w)]
  100. return cut_img
  101. def scale_rect(orig_rect,orig_shape,dest_shape):
  102. '''
  103. 对图像进行缩放时,对应的rectangle也要进行缩放
  104. :param orig_rect: 原始图像的rect=[x,y,w,h]
  105. :param orig_shape: 原始图像的维度shape=[h,w]
  106. :param dest_shape: 缩放后图像的维度shape=[h,w]
  107. :return: 经过缩放后的rectangle
  108. '''
  109. new_x=int(orig_rect[0]*dest_shape[1]/orig_shape[1])
  110. new_y=int(orig_rect[1]*dest_shape[0]/orig_shape[0])
  111. new_w=int(orig_rect[2]*dest_shape[1]/orig_shape[1])
  112. new_h=int(orig_rect[3]*dest_shape[0]/orig_shape[0])
  113. dest_rect=[new_x,new_y,new_w,new_h]
  114. return dest_rect
  115. def show_image_rect(win_name,image,rect):
  116. '''
  117. :param win_name:
  118. :param image:
  119. :param rect:
  120. :return:
  121. '''
  122. x, y, w, h=rect
  123. point1=(x,y)
  124. point2=(x+w,y+h)
  125. cv2.rectangle(image, point1, point2, (0, 0, 255), thickness=2)
  126. cv_show_image(win_name, image)
  127. def rgb_to_gray(image):
  128. image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
  129. return image
  130. def save_image(image_path, rgb_image,toUINT8=True):
  131. if toUINT8:
  132. rgb_image = np.asanyarray(rgb_image * 255, dtype=np.uint8)
  133. if len(rgb_image.shape) == 2: # 若是灰度图则转为三通道
  134. bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_GRAY2BGR)
  135. else:
  136. bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
  137. cv2.imwrite(image_path, bgr_image)
  138. def combime_save_image(orig_image, dest_image, out_dir,name,prefix):
  139. '''
  140. 命名标准:out_dir/name_prefix.jpg
  141. :param orig_image:
  142. :param dest_image:
  143. :param image_path:
  144. :param out_dir:
  145. :param prefix:
  146. :return:
  147. '''
  148. dest_path = os.path.join(out_dir, name + "_"+prefix+".jpg")
  149. save_image(dest_path, dest_image)
  150. dest_image = np.hstack((orig_image, dest_image))
  151. save_image(os.path.join(out_dir, "{}_src_{}.jpg".format(name,prefix)), dest_image)
  152. if __name__=="__main__":
  153. image_path="../dataset/test_images/src.jpg"
  154. image = read_image(image_path, resize_height=None, resize_width=None)
  155. image = rgb_to_gray(image)
  156. orig_shape=np.shape(image)#shape=(h,w)
  157. orig_rect=[50,100,100,200]#x,y,w,h
  158. print("orig_shape:{}".format(orig_shape))
  159. show_image_rect("orig",image,orig_rect)
  160. dest_image=resize_image(image,resize_height=None,resize_width=200)
  161. dest_shape=np.shape(dest_image)
  162. print("dest_shape:{}".format(dest_shape))
  163. dest_rect=scale_rect(orig_rect, orig_shape, dest_shape)
  164. show_image_rect("dest",dest_image,dest_rect)

发表评论

表情:
评论列表 (有 0 条评论,571人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python+opencv目标跟踪之鼠标

    项目介绍 目标:跟踪鼠标的移动,一开始采用深度学习的方法,但是效果不好,所以采用了下面的方法 操作描述:鼠标框住一个目标,然后按回车,框会跟随目标 本代码可

    相关 opencv鼠标操作

      opencv中的鼠标操作和滑动条的消息映射方式很类似,都是通过一个中介函数配合一个回调函数来实现。opencv中提供了setMouseCallback()函数,这个函数的作