python 从文件中读取图像显示,鼠标左键点击图像时输出图像的路径并将其保存至txt
时间: 2024-02-06 21:10:04 浏览: 29
可以使用Python的OpenCV库来实现从文件中读取图像并显示,以及监听鼠标事件并输出图像路径和保存至txt文件的功能。
以下是一个示例代码:
```python
import cv2
# 定义鼠标事件回调函数
def on_mouse(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
# 输出图像路径和保存至txt文件
img_path = param
print(img_path)
with open('img_paths.txt', 'a') as f:
f.write(img_path + '\n')
# 读取图像文件
img_path = 'test.jpg'
img = cv2.imread(img_path)
# 显示图像并设置鼠标事件回调函数
cv2.imshow('image', img)
cv2.setMouseCallback('image', on_mouse, param=img_path)
# 等待按下任意按键退出
cv2.waitKey(0)
# 关闭窗口并释放资源
cv2.destroyAllWindows()
```
该代码通过调用`cv2.imshow`函数显示图像,并通过`cv2.setMouseCallback`函数设置鼠标事件回调函数。当鼠标左键点击图像时,回调函数会将图像路径输出并将其保存至`img_paths.txt`文件中。
请注意,在运行代码之前,需要确保安装了OpenCV库。可以使用以下命令安装:
```
pip install opencv-python
```