如何让用户选择图像中的坐标并将这些坐标作为python中方法的参数?

时间:2019-08-07 19:22:05

标签: python opencv image-processing

对于我的图像处理项目,我想让用户在给定图像中选择一个点,并将该坐标作为参数来定义特定图像旋转的中心点。在下面的代码中,我定义了一种相对于给定位置参数围绕中心旋转图像的方法。您可以通过让用户定义旋转中心点来帮助我理解如何做吗?

  

在这里,如果row_position == 1/2和col_position == 1/4,则表示

     
    

y = 1/2 * total_number_of_rows_in_image,        x = 1/4 * total_number_of_columns_in_image

  
def rotateImage(baseImage,degree,rowPosition,colPosition):
    rowsNew,colsNew,channels=baseImage.shape
    centre=[rowPosition,colPosition]#these are fractional values

    rotationMatrix=cv2.getRotationMatrix2D(((colsNew*centre[1]),(rowsNew*centre[0])),degree,1)
    rotatedImg=cv2.warpAffine(baseImage,rotationMatrix,(colsNew,rowsNew))
    return rotatedImg

1 个答案:

答案 0 :(得分:0)

您可以使用鼠标回调函数来做到这一点:

def rotateImage(image, angle, center = None, scale = 1.0):
    (h, w) = image.shape[:2]
    if center is None:
        center = (w / 2, h / 2)
    # Perform the rotation
    M = cv2.getRotationMatrix2D(center, angle, scale)
    rotated = cv2.warpAffine(image, M, (w, h))
    return rotated

# stores mouse position in global variables ix(for x coordinate) and iy(for y coordinate) 
# on double click inside the image
def select_point(event,x,y,flags,param):
    global ix,iy
    if event == cv2.EVENT_LBUTTONDBLCLK: # captures left button double-click
        ix,iy = x,y

img = cv2.imread('sample.jpg')
cv2.namedWindow('image')
# bind select_point function to a window that will capture the mouse click
cv2.setMouseCallback('image', select_point)
cv2.imshow('image',img)
k = cv2.waitKey(0) & 0xFF
if k == ord('a'):
    # print(k)
    # print(ix, iy)
    rotated_img = rotateImage(img, 45, (ix, iy))
    cv2.imshow('rotated', rotated_img)

cv2.waitKey(0)     
cv2.destroyAllWindows()

只需双击图像内部,即可将xy坐标分别存储到ixiy全局变量中,然后按a按钮调用具有中心值的rotateImage函数并围绕该中心旋转图像。