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

标签 python image opencv image-processing computer-vision

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

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: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'


我正在尝试编写一个函数来在裁剪ROI之前验证坐标。目前,我的一些检查旨在确保:
  • (x,y,w,h)都是intfloat类型
  • xy> = 0
  • wh> 0

  • 有时仍然会引发错误,我缺少哪些检查?
    示例图片:

    码:
    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')
    

    最佳答案

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

    # get resolution and coordinates
    height, width = image.shape[:-1]
    xmin, ymin, w, h = coordinates
    xmax = xmin + w
    ymax = ymin + h
    
    # fetch roi
    if (xmin  >= 0) and (ymin >= 0) and (xmax < width) and (ymax < height):
      roi = image[ymin:ymax, xmin:xmax]
    

    关于python - 确保ROI裁剪坐标(x,y,w,h)有效且在Python OpenCV的范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63421624/

    相关文章:

    python - 编辑代码以根据条件创建过滤器,然后剥离条件

    c# - C#中直接从URL获取图片尺寸

    image - 从网站下载图像

    python - 如何检测检测到的形状OpenCV的颜色

    python - cv2.imread和os.listdir不起作用

    python - Boost.Python.ArgumentError:World.set(World, str) 中的 Python 参数类型与 C++ 签名不匹配:set(World {lvalue}, std::string)

    python - 在 SQL 中搜索一个字段以查看它是否包含 python 变量

    python - 从多索引中获取唯一索引的值

    image - 如何使用 Flutter 将 BASE64 字符串转换为 Image?

    opencv - 将CvSeq转换为CvMat