Python+OpenCV實(shí)現(xiàn)在圖像上繪制矩形
話不多說(shuō),直接上代碼
import copy
import cv2
import numpy as np
WIN_NAME = 'draw_rect'
class Rect(object):
def __init__(self):
self.tl = (0, 0)
self.br = (0, 0)
def regularize(self):
"""
make sure tl = TopLeft point, br = BottomRight point
"""
pt1 = (min(self.tl[0], self.br[0]), min(self.tl[1], self.br[1]))
pt2 = (max(self.tl[0], self.br[0]), max(self.tl[1], self.br[1]))
self.tl = pt1
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
@staticmethod
def __clip(value, low, high):
"""
clip value between low and high
Parameters
----------
value: a number
value to be clipped
low: a number
low limit
high: a number
high limit
Returns
-------
output: a number
clipped value
"""
output = max(value, low)
output = min(output, high)
return output
def shrink_point(self, x, y):
"""
shrink point (x, y) to inside image_for_show
Parameters
----------
x, y: int, int
coordinate of a point
Returns
-------
x_shrink, y_shrink: int, int
shrinked coordinate
"""
height, width = self.image_for_show.shape[0:2]
x_shrink = self.__clip(x, 0, width)
y_shrink = self.__clip(y, 0, height)
return (x_shrink, y_shrink)
def append(self):
"""
add a rect to rects list
"""
self.rects.append(copy.deepcopy(self.current_rect))
def pop(self):
"""
pop a rect from rects list
"""
rect = Rect()
if self.rects:
rect = self.rects.pop()
return rect
def reset_image(self):
"""
reset image_for_show using original image
"""
self.image_for_show = self.original_image.copy()
def draw(self):
"""
draw rects on image_for_show
"""
for rect in self.rects:
cv2.rectangle(self.image_for_show, rect.tl, rect.br,
color=self.color, thickness=self.thickness)
def draw_current_rect(self):
"""
draw current rect on image_for_show
"""
cv2.rectangle(self.image_for_show,
self.current_rect.tl, self.current_rect.br,
color=self.color, thickness=self.thickness)
def onmouse_draw_rect(event, x, y, flags, draw_rects):
if event == cv2.EVENT_LBUTTONDOWN:
# pick first point of rect
print('pt1: x = %d, y = %d' % (x, y))
draw_rects.left_button_down = True
draw_rects.current_rect.tl = (x, y)
if draw_rects.left_button_down and event == cv2.EVENT_MOUSEMOVE:
# pick second point of rect and draw current rect
draw_rects.current_rect.br = draw_rects.shrink_point(x, y)
draw_rects.reset_image()
draw_rects.draw()
draw_rects.draw_current_rect()
if event == cv2.EVENT_LBUTTONUP:
# finish drawing current rect and append it to rects list
draw_rects.left_button_down = False
draw_rects.current_rect.br = draw_rects.shrink_point(x, y)
print('pt2: x = %d, y = %d' % (draw_rects.current_rect.br[0],
draw_rects.current_rect.br[1]))
draw_rects.current_rect.regularize()
draw_rects.append()
if (not draw_rects.left_button_down) and event == cv2.EVENT_RBUTTONDOWN:
# pop the last rect in rects list
draw_rects.pop()
draw_rects.reset_image()
draw_rects.draw()
if __name__ == '__main__':
#image = np.zeros((256, 256, 3), np.uint8)
image = cv2.imread("111.jpg")
draw_rects = DrawRects(image, (0, 255, 0), 2)
cv2.namedWindow(WIN_NAME, 0)
cv2.setMouseCallback(WIN_NAME, onmouse_draw_rect, draw_rects)
while True:
cv2.imshow(WIN_NAME, draw_rects.image_for_show)
key = cv2.waitKey(30)
if key == 27: # ESC
break
cv2.destroyAllWindows()運(yùn)行效果

補(bǔ)充
當(dāng)然Python+OpenCV不僅能做到在圖像上繪制任意大小矩形,還能實(shí)現(xiàn)鼠標(biāo)點(diǎn)擊圖像時(shí)會(huì)顯示其坐標(biāo)值
下面是實(shí)現(xiàn)代碼
import cv2
import 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()運(yùn)行結(jié)果:

以上就是Python+OpenCV實(shí)現(xiàn)在圖像上繪制矩形的詳細(xì)內(nèi)容,更多關(guān)于Python OpenCV的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決keras使用cov1D函數(shù)的輸入問(wèn)題
這篇文章主要介紹了解決keras使用cov1D函數(shù)的輸入問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
Python中的 is 和 == 以及字符串駐留機(jī)制詳解
這篇文章主要介紹了Python中的 is 和 == 以及字符串駐留機(jī)制詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-06-06
python可以美化表格數(shù)據(jù)輸出結(jié)果的兩個(gè)工具
這篇文章主要介紹了python可以美化表格數(shù)據(jù)輸出結(jié)果的兩個(gè)工具,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-06-06
Python 實(shí)現(xiàn)使用dict 創(chuàng)建二維數(shù)據(jù)、DataFrame
下面小編就為大家分享一篇Python 實(shí)現(xiàn)使用dict 創(chuàng)建二維數(shù)據(jù)、DataFrame,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
Python中dictionary items()系列函數(shù)的用法實(shí)例
這篇文章主要介紹了Python中dictionary items()系列函數(shù)的用法,很實(shí)用的函數(shù),需要的朋友可以參考下2014-08-08

