How to correctly use cv2.imwrite to save an image in openCV with cv2.selectROI

TheTank picture TheTank · Aug 29, 2017 · Viewed 10.4k times · Source

I am trying out OpenCV's ROI function. With this I am trying to crop out a section of an image that I load. After that I am trying to save the image as well as show it. Showing it is not much of a problem, but saving it is. The image is being stored as a big black rectangle instead of the actual cropped image. Here is my code:

import cv2
import numpy as np
from skimage.transform import rescale, resize

if __name__ == '__main__' :

    # Read image
    im = cv2.imread("/Path/to/Image.jpg")
    img = resize(im, (400,400), mode='reflect') 
    # Select ROI
    r = cv2.selectROI(img)

    # Crop image
    imCrop = img[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])]

    # Save first, then Display cropped image
    cv2.imwrite("../../Desktop/Image.jpg", imCrop) # This is where there seems to be a problem
    cv2.imshow("im", imCrop)
    cv2.waitKey(0)

Can some one please help?

Answer

nathancy picture nathancy · Dec 18, 2019

cv2.selectROI returns the (x,y,w,h) values of a rectangle similar to cv2.boundingRect(). My guess is that the saved black rectangle is due to rounding issues when converting the bounding box coordinates to an int type. So just unpack the (x,y,w,h) coordinates directly and use Numpy slicing to extract the ROI. Here's a minimum working example to extract and save a ROI:

Input image -> Program to extract ROI -> Saved ROI

enter image description here enter image description here enter image description here

Code

import cv2

image = cv2.imread('1.jpg')
(x,y,w,h) = cv2.selectROI(image)
ROI = image[y:y+h, x:x+w]

cv2.imshow("ROI", ROI)
cv2.imwrite("ROI.png", ROI)
cv2.waitKey()