python使用鼠标在图片上画框

  • python rect.py 图片文件夹
  • 先左击左上角,再右击右下角,画出一个框
  • 结果保存在res文件夹
  • rect.py
import cv2, sys, os

path=sys.argv[1]
im=cv2.imread(path)
al=os.listdir(path)
al.sort()
if not os.path.exists('res'): os.makedirs('res')


def getInfo(event, x,y,flags,param):
  global xy
  if event == cv2.EVENT_LBUTTONDOWN:
    print x,y 
    xy=[]
    xy.append(x)
    xy.append(y)
  if event == cv2.EVENT_RBUTTONDOWN:
    if len(xy)!=2: 
    	print(len(xy))
    	return
    print x,y
    x1=xy[0]
    y1=xy[1]
    cv2.rectangle(param[0], (x1,y1), (x,y), (0,255,255), 2)
    cv2.imshow('image', param[0])
    cv2.waitKey(1)
    cv2.imwrite('res/'+param[1], param[0])
    xy=[]
    
for a in al:
	if a[-3:] != 'jpg': continue
	im=cv2.imread(path+'/'+a)
	cv2.namedWindow('image', 0)    
	cv2.resizeWindow('image', 1280, 720)
	cv2.imshow('image',im)
	cv2.setMouseCallback("image",getInfo, (im,a))
	cv2.waitKey(0)
	cv2.destroyAllWindows()

你可能感兴趣的:(小功能,python,opencv)