简体   繁体   中英

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

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?

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

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM