概述:实现图像的读取显示以及获取实时点击的像素坐标
import cv2
import os
import numpy as np
# 定义鼠标点击事件的回调函数
def mouse_callback(event, x, y, flags, param):
global canvas
global canvas1
if event == cv2.EVENT_LBUTTONDOWN:
# print(f"Clicked at pixel coordinates: ({x}, {y})")
# 获取实时图像固定区域,覆盖需要刷新的像素坐标显示区域
canvas[0:40, 0:185, :] = canvas1[0:40, 0:185, :]
cv2.putText(canvas, f"({x}, {y})", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow('Image Viewer', canvas)
def shouw_images():
while True:
global current_image_index
global current_image
global canvas
global canvas1
# 调整图像尺寸,保持固定比例
height, width, _ = current_image.shape
aspect_ratio = width / height
if aspect_ratio > (desired_width / desired_height):
new_width = desired_width
new_height = int(desired_width / aspect_ratio)
else:
new_height = desired_height
new_width = int(desired_height * aspect_ratio)
# resize 图像
resized_image = cv2.resize(current_image, (new_width, new_height))
# 创建一个固定尺寸的画布
canvas = np.zeros((desired_height, desired_width, 3), dtype=np.uint8)
x_offset = int((desired_width - new_width) / 2)
y_offset = int((desired_height - new_height) / 2)
# 将reseze图像复制到画布中心
canvas[y_offset:y_offset + new_height, x_offset:x_offset + new_width] = resized_image
canvas1[0:40, 0:185, :] = canvas[0:40, 0:185, :]
# 创建一个绑定鼠标事件的窗口
cv2.namedWindow('Image Viewer')
cv2.setMouseCallback('Image Viewer', mouse_callback)
# 显示当前图像
cv2.imshow('Image Viewer', canvas)
# 等待用户按键操作
key = cv2.waitKey(0)
# 如果按下 'n' 键,显示下一张图像
if key == ord('n'):
current_image_index = (current_image_index + 1) % len(image_files)
current_image = cv2.imread(os.path.join(image_folder, image_files[current_image_index]))
# 如果按下 'p'键,显示上一张图像
elif key == ord('p'):
current_image_index = (current_image_index - 1) % len(image_files)
current_image = cv2.imread(os.path.join(image_folder, image_files[current_image_index]))
# 如果按下 's'键,显示上一张图像
elif key == ord('s'):
save_path = os.path.join(image_folder, f"edited_{image_files[current_image_index]}")
cv2.imwrite(save_path, current_image)
print(f"Saved edited image as {save_path}")
# 如果按下 'q' 键,退出程序
elif key == ord('q'):
break
# 定义固定尺寸
desired_width = 1000
desired_height = 600
# 定义图像文件夹路径
image_folder = '/home/xuan/Data/01_AI_data/00_Study/opencv_practice/IMAGES'
# 获取图像文件列表
image_files = os.listdir(image_folder)
# 定义当前显示图像的索引
current_image_index = 0
# 加载第一张图像
current_image = cv2.imread(os.path.join(image_folder, image_files[current_image_index]))
canvas = np.zeros((desired_height, desired_width, 3), dtype=np.uint8)
canvas1 = np.zeros((desired_height, desired_width, 3), dtype=np.uint8)
shouw_images()
# 关闭窗口
cv2.destroyAllWindows()