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

2024-04-28 14:14:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

In here if row_position == 1/2 and col_position == 1/4 it means

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

Tags: of用户in图像imagenumber参数定义
1条回答
网友
1楼 · 发布于 2024-04-28 14:14:07

您可以使用鼠标回调函数:

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函数,并围绕此中心旋转图像。你知道吗

相关问题 更多 >