如何设置鼠标滚动来放大/缩小图像?[opencv-python]

w8f9ii69  于 8个月前  发布在  Python
关注(0)|答案(1)|浏览(73)

我有一个代码,当我想使用鼠标滚动来放大/缩小图像时,它可以很好地工作,但它只对左上角这样做:

import cv2
import pyautogui

img_ = cv2.imread(r'path_to_file')

# Adjust the image to fit the screen
_, screen_height = pyautogui.size()
new_height = int(screen_height * 1.1)
new_width = int(new_height * img_.shape[1] / img_.shape[0])
img = cv2.resize(img_, (new_width, new_height))

def select_roi(event, x, y, flags, param):
    global img, new_height, new_width
    img_copy = img.copy()
    if event == cv2.EVENT_MOUSEWHEEL:
        if flags > 0:
            new_height = int(new_height * 1.1)
        else:
            new_height = int(new_height / 1.1)
        new_width = int(new_height * img_copy.shape[1] / img_copy.shape[0])
        img = cv2.resize(img_, (new_width, new_height))
        cv2.imshow('Selected area', img)

cv2.namedWindow('Selected area')
cv2.setMouseCallback('Selected area', select_roi)
cv2.imshow('Selected area', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

最好的解决方案是能够在鼠标光标当前位于图像上的位置缩放图像(例如,当我们在Windows上打开任何图像并使用组合键“center”+“mouse scroll”时会发生这种情况)。
然而,一个足够的方法是让“Shift+Scroll”组合键向图像的右下角缩放。
我需要这个解决方案,因为我想在图像中选择我感兴趣的特定表单字段,这些字段通常太小,不放大就无法捕获。如果任何字段位于图像的下部,那么只向左上角放大是不够的。

hgc7kmma

hgc7kmma1#

我知道我有点晚了,但这可能会有帮助。我改变了你的代码一点点,但我想这是你要找的:

import cv2

base_img = cv2.imread(r"path_to_file")

img = base_img.copy()
zoom = 1
min_zoom = 1
max_zoom = 5

def select_roi(event, x, y, flags, param):
    global base_img, zoom, min_zoom, max_zoom
    if event == cv2.EVENT_MOUSEWHEEL:
        if flags > 0:
            zoom *= 1.1
            zoom = min(zoom, max_zoom)
        else:
            zoom /= 1.1
            zoom = max(zoom, min_zoom)

        img = base_img.copy()

        # Calculate zoomed-in image size
        new_width = round(img.shape[1] / zoom)
        new_height = round(img.shape[0] / zoom)

        # Calculate offset
        x_offset = round(x - (x / zoom))
        y_offset = round(y - (y / zoom))

        # Crop image
        img = img[
            y_offset : y_offset + new_height,
            x_offset : x_offset + new_width,
        ]

        # Stretch image to full size
        img = cv2.resize(img, (base_img.shape[1], base_img.shape[0]))
        cv2.imshow("Selected area", img)

cv2.namedWindow("Selected area")
cv2.setMouseCallback("Selected area", select_roi)
cv2.imshow("Selected area", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

因为OpenCV处理键盘和鼠标事件的方式不同,所以我只使用鼠标滚轮进行滚动。

相关问题