首先点击两个点画一个矩形窗口,接下来继续点两点画个直线,画完之后按下“x”键则会用liang方法裁剪直线,将在窗口外的部分除去,按下”q”退出
import cv2
import numpy as np
import time
import math
img = np.zeros((600, 800, 3), np.uint8)#背景
flag,count=False,2
ptl1x,ptl1y,ptl2x,ptl2y=0,0,0,0
ptR1x,ptR1y,ptR2x,ptR2y=0,0,0,0
def LiangCut(x1,y1,x2,y2,xl,yb,xr,yt):
dx=x2-x1
dy=y2-y1
p=[1,-dx,dx,-dy,dy]
q=[1,x1-xl,xr-x1,y1-yb,yt-y1]
print(p,q,xl,yb,xr,yt)
cv2.line(img,(x1,y1),(x2,y2),(0,0,0))
if (dx==0 and (q[1]<0 or q[2]<0)) or (dy==0 and (q[3]<0 or q[4]<0)):
return
umax,umin=0,1
for i in range(1,5):
if p[i]>0:
umin=min(umin,q[i]/p[i])
elif p[i]<0:
umax=max(umax,q[i]/p[i])
print(umax,umin)
if umax>umin:
return
print("in the rect!")
x1,y1,x2,y2=int(x1+umax*dx),int(y1+umax*dy),int(x1+umin*dx),int(y1+umin*dy)
str1 = '(x:'+ str(x1) + ',y:'+ str(y1) + ')'
str2 = '(x:'+ str(x2) + ',y:'+ str(y2) + ')'
cv2.putText(img,str1 , (x1, y1), cv2.FONT_HERSHEY_PLAIN,1.0, (0, 0, 255), thickness=1)
cv2.putText(img,str2 , (x2, y2), cv2.FONT_HERSHEY_PLAIN,1.0, (0, 0, 255), thickness=1)
cv2.line(img,(x1,y1),(x2,y2),(255,255,255))
def draw_func(event, x, y, flags, param):
global flag,count,ptl1x,ptl1y,ptl2x,ptl2y,ptR1x,ptR1y,ptR2x,ptR2y
if event == cv2.EVENT_LBUTTONDOWN:
print('(x:',x,',y:',y,')')
cv2.circle(img,(x,y),1,(0,255,0),thickness=5)
if count==2:
count-=1
ptR1x,ptR1y=x,y
elif count==1:
count-=1
ptR2x,ptR2y=x,y
cv2.rectangle(img,(ptR1x,ptR1y),(ptR2x,ptR2y),(255,0,255))
else:
if flag:
ptl2x,ptl2y=x,y
cv2.line(img,(ptl1x,ptl1y),(ptl2x,ptl2y),(255,255,255))
flag=False
else:
ptl1x,ptl1y=x,y
flag=True
cv2.namedWindow('src')
cv2.setMouseCallback('src',draw_func)
while(1):
cv2.imshow('src',img)
code=cv2.waitKey(100)
if code == ord('q'):#按下q退出
break
elif code == ord('x'):#按下x裁剪
LiangCut(ptl1x,ptl1y,ptl2x,ptl2y,ptR1x,ptR1y,ptR2x,ptR2y)
cv2.destroyAllWindows()