【发布时间】:2018-11-22 13:18:26
【问题描述】:
我正在尝试向用户显示图像并要求单击用户的矩形的 4 个点,一旦用户完成,他将按“c”并退出,我的脚本应返回用户的触摸点。
对于这种方法,我使用 OpenCV 在下面编写了脚本,但不确定如何为此目的制作可迭代的类,可能是我对某些 OO 技术部分有误,但要求和逻辑是正确的,因为当不在类内部创建时功能正常。
代码:
class mouse_select_points:
''' Select 4 user points from user and crop to straighten'''
__depends__ = ['img_path']
__provides__ = ['ratio','image_resized','click_points']
def __init__(self, thickness=2,shape=(400,600),click_count=0,click_points=[],img_path=""):
self.thickness = thickness
self.shape = shape
self.lent = click_count
self.refPt = click_points
self.img = img_path
self.font = cv2.FONT_HERSHEY_SIMPLEX
def __call__(self):
image = cv2.imread(self.img)
print("first loaded image size:",image.shape)
orig_resized = image.copy() #create a copy of resized image
ratio = image.shape[1] / 600.0
self.shape = image.shape
cv2.namedWindow("image")
cv2.setMouseCallback("image", self._click_and_crop, param = [image] ) #setting param as image to be sent to mouse click function callback
# keep looping until the 'c' key is pressed
while True:
# display the image and wait for a keypress
cv2.imshow("image", image)
cv2.putText(image,"press 'c' to crop or 'r' to reset",(10,15), self.font, .5,(255,255,255),1,cv2.LINE_AA)
key = cv2.waitKey(1) & 0xFF
# if the 'c' key is pressed, break from the loop
elif key == ord("c") and self.lent == 4:
break
return ratio,orig_resized,self.refPt
def _click_and_crop(self,event, x, y, flags, param):
image = param[0]
# if the left mouse button was clicked, record the starting
# (x, y) coordinates and indicate that cropping is being performed
if event == cv2.EVENT_LBUTTONDOWN:
self.refPt.append([x, y])
cv2.circle(image,(int(x),int(y)),self.thickness,(255,1,255),-1)
self.lent += 1
print("inside if")
cv2.imshow("image", image)
##testing
ratio,orig_image = mouse_select_points(img_path=r"Image1.JPG")
【问题讨论】:
-
您能否更清楚地说明这一点:
but not sure how to make class for this purpose iterable。你想重复selection op吗?或者你想返回可迭代的结果(我认为 self.refPt 已经是可迭代的了)?
标签: python-3.x opencv vision