Python 确保ROI裁剪坐标(x、y、w、h)有效且在OpenCV的范围内

Python 确保ROI裁剪坐标(x、y、w、h)有效且在OpenCV的范围内,python,image,opencv,image-processing,computer-vision,Python,Image,Opencv,Image Processing,Computer Vision,给定从图像裁剪ROI的(x,y,w,h)坐标,如何确保给定坐标有效?例如: image = cv2.imread('1.jpeg') x,y,w,h = 0,0,300,300 ROI = image[y:y+h,x:x+w] cv2.imshow('ROI', ROI) cv2.waitKey() 如果(x,y,w,h)坐标无效,它将抛出此错误: cv2.error:OpenCV(4.0.0)C:\projects\OpenCV python\OpenCV\modules\highgui\s

给定从图像裁剪ROI的
(x,y,w,h)
坐标,如何确保给定坐标有效?例如:

image = cv2.imread('1.jpeg')
x,y,w,h = 0,0,300,300
ROI = image[y:y+h,x:x+w]
cv2.imshow('ROI', ROI)
cv2.waitKey()
如果
(x,y,w,h)
坐标无效,它将抛出此错误:

cv2.error:OpenCV(4.0.0)C:\projects\OpenCV python\OpenCV\modules\highgui\src\window.cpp:350:错误:(-215:断言失败)函数“cv::imshow”中的size.width>0和size.height>0

我正在尝试编写一个函数,在裁剪ROI之前验证坐标。目前,我的一些检查是为了确保:

  • (x,y,w,h)
    都是
    int
    float
    类型
  • x
    y
    为>=0
  • w
    h
    均>0
  • 有时它仍然抛出错误,我缺少什么检查

    示例图像:

    代码:


    您可以使用图像分辨率检查坐标是否在图像范围内:

    #获取分辨率和坐标
    高度,宽度=图像。形状[:-1]
    xmin,ymin,w,h=坐标
    xmax=xmin+w
    ymax=ymin+h
    #获取投资回报率
    如果(xmin>=0)和(ymin>=0)以及(xmax
    import cv2
    
    def validate_ROI_coordinates(coordinates):
        # (x,y) is top left coordinates
        # Top right corner is is (x + w)
        # Bottom left corner is (y + h) 
        
        x,y,w,h = coordinates
        
        # Ensure its a number, not boolean or string type
        def int_or_float(s):
            try:
                i = int(s)
                return True
            except ValueError:
                try:
                    f = float(s)
                    return True
                except:
                    return False
        
        def within_bounds(x,y,w,h):
            # Ensure that x and y are >= 0
            if x >= 0 and y >= 0:
                # Ensure w and h are > 0 ( can be any positive number)
                if w > 0 and h > 0:
                    return True
            else:
                return False
        
        if all(int_or_float(value) for value in coordinates) and within_bounds(x,y,w,h):
            return True
        else:
            return False
    
    image = cv2.imread('1.jpeg')
    print(image.shape)
    x,y,w,h = 500,0,6600,300
    coordinates = (x,y,w,h)
    
    if validate_ROI_coordinates(coordinates):
        ROI = image[y:y+h,x:x+w]
        cv2.imshow('ROI', ROI)
        cv2.waitKey()
    else:
        print('Invalid ROI coordinates')