使用python cv2,打开一张图片,用鼠标在图片上依次点四个点,并记下四个点的坐标,存入pts = np.array([(), (), (), ()}
时间: 2024-10-15 11:24:15 浏览: 22
要使用Python的OpenCV库`cv2`来实现这个功能,你可以按照以下步骤操作:
1. 首先导入所需的模块[^1]:
```python
import cv2
import numpy as np
```
2. 定义图片路径:
```python
yes_path = "/path/to/your/image.jpg" # 替换为实际图片文件路径
```
3. 读取图片并显示:
```python
im = cv2.imread(yes_path)
cv2.imshow("Select points", im) # 显示图片并等待用户交互
```
4. 创建一个空数组来存储四个点的坐标:
```python
# 初始化一个空的numpy数组,形状为(4, 2),表示四个点(x, y)
pts = np.zeros((4, 2), dtype=np.int32)
```
5. 当用户按下键盘上的任意键时,开始选择点:
```python
# 使用cv2.setMouseCallback函数,当鼠标点击事件发生时调用回调函数
def select_points(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN: # LEFT CLICK
pts[0] = (x, y) # 存储第一个点
elif event == cv2.EVENT_LBUTTONUP: # LEFT RELEASE
if len(pts) > 0: # 如果已有至少一个点
# 存储最后一个点并退出选择模式
pts[-1] = (x, y)
break
cv2.namedWindow('Select points')
cv2.setMouseCallback('Select points', select_points)
```
6. 循环等待用户选择四个点,直到用户释放鼠标:
```python
while True:
cv2.imshow('Select points', im)
key = cv2.waitKey(1) & 0xFF
if key == ord('q') or key == 27: # 按Q键或Esc退出
break
```
7. 最后,关闭窗口并可能保存选区到`pts`变量:
```python
cv2.destroyAllWindows()
```
完整代码示例:
```python
import cv2
import numpy as np
yes_path = "/path/to/your/image.jpg"
im = cv2.imread(yes_path)
cv2.imshow("Select points", im)
# 初始化点坐标数组
pts = np.zeros((4, 2), dtype=np.int32)
def select_points(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
pts[0] = (x, y)
elif event == cv2.EVENT_LBUTTONUP:
if len(pts) > 0:
pts[-1] = (x, y)
break
cv2.namedWindow('Select points')
cv2.setMouseCallback('Select points', select_points)
while True:
cv2.imshow('Select points', im)
key = cv2.waitKey(1) & 0xFF
if key == ord('q') or key == 27:
break
cv2.destroyAllWindows()
```
阅读全文