ASCII码 ASCII码

Python+OpenCV实现在图像上绘制矩形

发布于:2022-03-22 09:36:15  栏目:技术文档

话不多说,直接上代码`import copyimport cv2import numpy as np

WIN_NAME = ‘draw_rect’

class Rect(object): def init(self): self.tl = (0, 0) self.br = (0, 0)

  1. def regularize(self):
  2. """
  3. make sure tl = TopLeft point, br = BottomRight point
  4. """
  5. pt1 = (min(self.tl[0], self.br[0]), min(self.tl[1], self.br[1]))
  6. pt2 = (max(self.tl[0], self.br[0]), max(self.tl[1], self.br[1]))
  7. self.tl = pt1
  8. self.br = pt2

class DrawRects(object): def init(self, image, color, thickness=1): self.original_image = image self.image_for_show = image.copy() self.color = color self.thickness = thickness self.rects = [] self.current_rect = Rect() self.left_button_down = False

  1. @staticmethod
  2. def __clip(value, low, high):
  3. """
  4. clip value between low and high
  5. Parameters
  6. ----------
  7. value: a number
  8. value to be clipped
  9. low: a number
  10. low limit
  11. high: a number
  12. high limit
  13. Returns
  14. -------
  15. output: a number
  16. clipped value
  17. """
  18. output = max(value, low)
  19. output = min(output, high)
  20. return output
  21. def shrink_point(self, x, y):
  22. """
  23. shrink point (x, y) to inside image_for_show
  24. Parameters
  25. ----------
  26. x, y: int, int
  27. coordinate of a point
  28. Returns
  29. -------
  30. x_shrink, y_shrink: int, int
  31. shrinked coordinate
  32. """
  33. height, width = self.image_for_show.shape[0:2]
  34. x_shrink = self.__clip(x, 0, width)
  35. y_shrink = self.__clip(y, 0, height)
  36. return (x_shrink, y_shrink)
  37. def append(self):
  38. """
  39. add a rect to rects list
  40. """
  41. self.rects.append(copy.deepcopy(self.current_rect))
  42. def pop(self):
  43. """
  44. pop a rect from rects list
  45. """
  46. rect = Rect()
  47. if self.rects:
  48. rect = self.rects.pop()
  49. return rect
  50. def reset_image(self):
  51. """
  52. reset image_for_show using original image
  53. """
  54. self.image_for_show = self.original_image.copy()
  55. def draw(self):
  56. """
  57. draw rects on image_for_show
  58. """
  59. for rect in self.rects:
  60. cv2.rectangle(self.image_for_show, rect.tl, rect.br,
  61. color=self.color, thickness=self.thickness)
  62. def draw_current_rect(self):
  63. """
  64. draw current rect on image_for_show
  65. """
  66. cv2.rectangle(self.image_for_show,
  67. self.current_rect.tl, self.current_rect.br,
  68. color=self.color, thickness=self.thickness)

def onmouse_draw_rect(event, x, y, flags, draw_rects): if event == cv2.EVENT_LBUTTONDOWN:

  1. # pick first point of rect
  2. print('pt1: x = %d, y = %d' % (x, y))
  3. draw_rects.left_button_down = True
  4. draw_rects.current_rect.tl = (x, y)
  5. if draw_rects.left_button_down and event == cv2.EVENT_MOUSEMOVE:
  6. # pick second point of rect and draw current rect
  7. draw_rects.current_rect.br = draw_rects.shrink_point(x, y)
  8. draw_rects.reset_image()
  9. draw_rects.draw()
  10. draw_rects.draw_current_rect()
  11. if event == cv2.EVENT_LBUTTONUP:
  12. # finish drawing current rect and append it to rects list
  13. draw_rects.left_button_down = False
  14. draw_rects.current_rect.br = draw_rects.shrink_point(x, y)
  15. print('pt2: x = %d, y = %d' % (draw_rects.current_rect.br[0],
  16. draw_rects.current_rect.br[1]))
  17. draw_rects.current_rect.regularize()
  18. draw_rects.append()
  19. if (not draw_rects.left_button_down) and event == cv2.EVENT_RBUTTONDOWN:
  20. # pop the last rect in rects list
  21. draw_rects.pop()
  22. draw_rects.reset_image()
  23. draw_rects.draw()

if name == ‘main‘:

  1. #image = np.zeros((256, 256, 3), np.uint8)
  2. image = cv2.imread("111.jpg")
  3. draw_rects = DrawRects(image, (0, 255, 0), 2)
  4. cv2.namedWindow(WIN_NAME, 0)
  5. cv2.setMouseCallback(WIN_NAME, onmouse_draw_rect, draw_rects)
  6. while True:
  7. cv2.imshow(WIN_NAME, draw_rects.image_for_show)
  8. key = cv2.waitKey(30)
  9. if key == 27: # ESC
  10. break
  11. cv2.destroyAllWindows()`

运行效果补充

当然Python+OpenCV不仅能做到在图像上绘制任意大小矩形,还能实现鼠标点击图像时会显示其坐标值

Python客栈送红包、纸质书

下面是实现代码`import cv2import numpy as np

img = cv2.imread(“111.jpg”)

print img.shape

def on_EVENT_LBUTTONDOWN(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: xy = “%d,%d” % (x, y) print xy cv2.circle(img, (x, y), 1, (255, 0, 0), thickness=-1) cv2.putText(img, xy, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), thickness=1) cv2.imshow(“image”, img)

cv2.namedWindow(“image”,cv2.WINDOW_KEEPRATIO)cv2.setMouseCallback(“image”, on_EVENT_LBUTTONDOWN)cv2.imshow(“image”, img)

while (True): try: cv2.waitKey(100) except Exception: cv2.destroyWindow(“image”) break

cv2.waitKey(0)cv2.destroyAllWindow()`运行结果:以上就是Python+OpenCV实现在图像上绘制矩形的详细内容

相关推荐
阅读 +