OpenCV python裁剪图像

时间:2017-01-25 18:32:28

标签: python image opencv

我创建了黑色图像,而不是在此图像中绘制了一个红色矩形。之后,我裁剪了这个图像,并使用该命令在裁剪图像中绘制了另一个矩形。 cv2.rectangle(crop,(50,50),(150,150),(0,0,255),3)

为什么当我在结尾显示时,第二个矩形出现在原始图像中?我希望看到第一个矩形。

import cv2
import numpy as np

#create image
image = np.zeros((400,400,3), np.uint8)

#draw rectangle into original image
cv2.rectangle(image,(100,100),(300,300),(0,0,255),3)

#crop image
crop = image[100:300,100:300]

#draw rectangle into cropped image
cv2.rectangle(crop,(50,50),(150,150),(0,0,255),3)
cv2.imshow('Result', image)
cv2.waitKey()    

cv2.destroyAllWindows()

3 个答案:

答案 0 :(得分:2)

crop = image[100:300,100:300]在原始图片上创建视图而不是新对象。修改该视图将修改基础原始图像。有关详细信息,请参阅http://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html

您可以通过在裁剪时创建副本来解决此问题: crop = image[100:300,100:300].copy()

注意:image[100:300,100:300]参数为y: y+h, x: x+w not x: x+w, y: y+h

答案 1 :(得分:0)

如果要保存裁剪的图像,只需添加以下代码:

cv2.imwrite("Cropped.jpg", roi)

after cv2.imshow("Cropped", roi)

我希望这会有所帮助。

答案 2 :(得分:-1)

您可以使用

轻松地在python中裁剪图像
roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]

要获得这两点,您可以拨打cv2.setMouseCallback("image", mouse_crop)。 这个函数是这样的

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)

您可以从此处获取详细信息:Mouse Click and Cropping using Python