实际效果如下图
import cv2
name='mf.jpg'
def mouse(event,x,y,flags,param):
global tap,ls,x0,y0,x1,y1
if event == cv2.EVENT_LBUTTONDOWN and tap == 0:
(x0,y0)=(x,y)
tap = 1
print(x0,y0)
#cv2.destroyWindow('mb')
elif event == cv2.EVENT_MOUSEMOVE and tap == 1:
#print(x1,y1)
(x1,y1)=(x,y)
ls = img.copy()
cv2.rectangle(ls,(x0,y0),(x1,y1),(0,0,255),1)
if x0>x1:
xs=int(x1)
xe=int(x0)
else:
xs=int(x0)
xe=int(x1)
if y0>y1:
ye=int(y0)
ys=int(y1)
else:
ye=int(y1)
ys=int(y0)
mb = img[ys:ye,xs:xe]
if len(mb)<10:
pass
else:
cv2.imshow('mb',mb)
elif event == cv2.EVENT_LBUTTONDOWN and tap == 1:
(x1,y1)=(x,y)
ls = img.copy()
cv2.rectangle(ls,(x0,y0),(x1,y1),(0,0,255),1)
#print(x0,y0,x1,y1)
if x0>x1:
xs=int(x1)
xe=int(x0)
else:
xs=int(x0)
xe=int(x1)
if y0>y1:
ye=int(y0)
ys=int(y1)
else:
ye=int(y1)
ys=int(y0)
mb = img[ys:ye,xs:xe]
cv2.imwrite('mb.jpg',mb)
cv2.imshow('mb',mb)
print('保存成功,图片:',"mb.jpg")
tap = 0
tap = 0
img = cv2.imread(name)
ls = img.copy()
cv2.imshow('image',ls)
cv2.setMouseCallback('image',mouse,img.copy())
while True:
cv2.imshow('image',ls)
if cv2.waitKey(20)&0xff==ord('q'):
break
cv2.destroyAllWindows()