python - 如何让用户选择图像中的坐标并将这些坐标作为python中方法的参数?
问题描述
对于我的图像处理项目,我想让用户在给定图像中选择一个点并将该坐标作为参数来定义特定图像旋转的中心点。在下面的代码中,我定义了一种方法,可以根据给定的位置参数围绕中心旋转图像。你能通过让用户定义旋转中心点来帮助我理解如何做到这一点吗?
在这里如果 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
解决方案
您可以使用鼠标回调函数来做到这一点:
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()
只需在图像内部双击将x
和y
坐标分别存储到ix
和iy
全局变量中,然后按a
按钮调用rotateImage
具有中心值的函数并围绕该中心旋转图像。
推荐阅读
- python - 如何从 GCS 读取 json gzipped 文件并写入表?
- php - 在 HTTP POST 中修改 JSON 文件后,如何从 chartjs 重新加载数据
- node.js - 无法仅在没有 serverToServerKeyAuth 的情况下使用 apiTokenAuth 对 CloudKit JS 进行身份验证
- c - 服务器程序卡在 read() 函数上,但 write() 函数在客户端程序中运行良好
- elasticsearch - Elasticsearch 自动查找查询
- javascript - 谷歌表格批量更新无效值错误
- wpf - “'=' 附近的语法不正确。” 删除
- javascript - 可触摸组件中的 this/context 问题
- node.js - Ionic 3 项目中的 Node JS 和 SASS 不兼容问题
- c++ - 打印文本导致内存泄漏