hory
hory

Reputation: 305

OpenCV python cropping image

I've created black image, than I drew a red rectangle into this image. Afterwards I cropped this image and drew a another rectangle into the cropped image using the command. cv2.rectangle(crop,(50,50),(150,150),(0,0,255),3)

Why does this second rectangle appears in the original image when I show it at the end? I expected to see just the first rectangle.

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()

Upvotes: 1

Views: 27779

Answers (3)

Martin Valgur
Martin Valgur

Reputation: 6322

crop = image[100:300,100:300] creates a view on the original image instead of a new object. Modifying that view will modify the underlying original image. See http://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html for more details.

You can resolve this issue by creating a copy when cropping: crop = image[100:300,100:300].copy().

Note: image[100:300,100:300] parameters are y: y+h, x: x+w not x: x+w, y: y+h

Upvotes: 6

if you want to save the cropped image, just add this code:

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

after cv2.imshow("Cropped", roi)

I hope this helps.

Upvotes: 0

Md. Hanif Ali Sohag
Md. Hanif Ali Sohag

Reputation: 59

you can easily crop the image in python by using

roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]

In order to get the two points you can call cv2.setMouseCallback("image", mouse_crop). The function is something like this

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)

You can get details from here : Mouse Click and Cropping using Python

Upvotes: -1

Related Questions