自制图片画框
import cv2 as cv
调用函数,输入图片路径
rect_oneimg=setRectsInOneImg(imgpath)
单张图片画多个框,用到了后面画单个框的函数 setOneRect
def setRectsInOneImg(imgpath):"""返回一张图片所有的矩形框返回格式: [[(x0,y0),(x1,y1)],[(x0,y0),(x1,y1)],[(x0,y0),(x1,y1)],]"""rects = [] #一个图片的所有矩形的两个顶点srcimg = cv.imread(imgpath)while True:rect = setOneRect(srcimg,rects)if rect !=[(),()]:rects.append(rect)print(rects)else:breakreturn rects
画单个框
def setOneRect(img,rects=None):"""在一张图片上画一个矩形,可以重复画,按回车确认所画矩形如果直接回车返回空"""if rects is not None:img = drawRectOnImg(img,rects)windowName = 'img'global p0,p1p0, p1=(),()def draw_circle(event, x, y, flags, param):global p0,p1# imgcopy=imgimgcopy=img.copy()if event == cv.EVENT_LBUTTONDOWN:p0 = (x, y)print('起点:{}'.format(p0))cv.circle(imgcopy,p0,radius,red,thickness)cv.imshow(windowName,imgcopy)elif event==cv.EVENT_MOUSEMOVE and (flags&cv.EVENT_LBUTTONDOWN):cv.rectangle(imgcopy,p0,(x,y),red,thickness=thickness)cv.imshow(windowName,imgcopy)elif event == cv.EVENT_LBUTTONUP:p1=(x,y)print('终点:{}'.format(p1))cv.rectangle(imgcopy,p0,p1,red,thickness=thickness)cv.imshow(windowName,imgcopy)cv.namedWindow(windowName)cv.imshow(windowName, img)cv.moveWindow(windowName, -1400, 0)cv.setMouseCallback(windowName, draw_circle)key = cv.waitKey(0)if key == 13: # Enterrect=[p0,p1]print('返回:{}'.format(rect))return rectelse:print('重试!')return setOneRect(img,rects)
其中用到了鼠标点击图片的响应,具体可以参考:
OpenCV-python 用鼠标在图片上标记位置并返回坐标