简体   繁体   English

如何正确使用 cv2.imwrite 将图像保存在带有 cv2.selectROI 的 openCV 中

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

I am trying out OpenCV's ROI function.我正在尝试 OpenCV 的 ROI 功能。 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() . cv2.selectROI返回类似于cv2.boundingRect()的矩形的(x,y,w,h)值。 My guess is that the saved black rectangle is due to rounding issues when converting the bounding box coordinates to an int type.我的猜测是保存的黑色矩形是由于将边界框坐标转换为int类型时的舍入问题。 So just unpack the (x,y,w,h) coordinates directly and use Numpy slicing to extract the ROI.所以直接解包(x,y,w,h)坐标,使用Numpy切片提取ROI即可。 Here's a minimum working example to extract and save a ROI:这是提取和保存 ROI 的最小工作示例:

Input image -> Program to extract ROI -> Saved ROI输入图像->提取 ROI 的程序->保存的 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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