簡體   English   中英

確保 ROI 裁剪坐標 (x,y,w,h) 有效且在范圍內

[英]Ensure ROI crop coordinates (x,y,w,h) are valid and within bounds Python OpenCV

給定(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。 function 'cv::imshow' 中的高度>0

我正在嘗試編寫 function 以在裁剪 ROI 之前驗證坐標。 目前,我的一些檢查是為了確保:

  1. (x,y,w,h)都是intfloat類型
  2. xy >= 0
  3. 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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM