Python cv2 90:90纵横比矩形到裁剪图像

问题描述 投票:0回答:2

我正在编写一个程序来裁剪图像,我的问题是我希望该矩形具有特定的宽高比(90:90),并且可以制作矩形而不是鼠标,使用鼠标滚轮更改其大小并确认用鼠标单击?

import cv2
import numpy as np

cropping = False

x_start, y_start, x_end, y_end = 0, 0, 0, 0

image = cv2.imread('example.jpg')
oriImage = image.copy()


def mouse_crop(event, x, y, flags, param):
    # grab references to the global variables
    global x_start, y_start, x_end, y_end, cropping

    # if the left mouse button was DOWN, start RECORDING
    # (x, y) coordinates and indicate that cropping is being
    if event == cv2.EVENT_LBUTTONDOWN:
        x_start, y_start, x_end, y_end = x, y, x, y
        cropping = True

    # Mouse is Moving
    elif event == cv2.EVENT_MOUSEMOVE:
        if cropping == True:
            x_end, y_end = x, y

    # if the left mouse button was released
    elif event == cv2.EVENT_LBUTTONUP:
        # record the ending (x, y) coordinates
        x_end, y_end = x, y
        cropping = False # cropping is finished

        refPoint = [(x_start, y_start), (x_end, y_end)]

        if len(refPoint) == 2: #when two points were found
            roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]
            cv2.imshow("Cropped", roi)

cv2.namedWindow("image")
cv2.setMouseCallback("image", mouse_crop)

while True:

    i = image.copy()

    if not cropping:
        cv2.imshow("image", image)

    elif cropping:
        cv2.rectangle(i, (x_start, y_start), (x_end, y_end), (255, 0, 0), 2)
        cv2.imshow("image", i)

    cv2.waitKey(1)

# close all open windows
cv2.destroyAllWindows()

python crop rectangles aspect-ratio
2个回答
0
投票

这是您可以用来执行此操作的基本结构。首次单击时创建一个初始矩形,通过向上或向下滚动来调整矩形的大小,然后再次单击以完成裁剪。您需要添加一些检查,以在矩形超出图像范围且矩形“小于零”时对其进行限制。


0
投票

谢谢:),但是我还有一个问题,我的代码现在看起来像这样:

© www.soinside.com 2019 - 2024. All rights reserved.