簡體   English   中英

如何在僅由 cv2.minAreaRect 創建的框內進行圖像處理?

[英]How to do image processing inside box created by cv2.minAreaRect only?

我在原始圖像中繪制了一個旋轉的矩形。 是否可以只在旋轉后的矩形框中進行圖像處理而不從原始圖像中裁剪掉它? 在此處輸入圖像描述 在此處輸入圖像描述

original = cv2.imread(r'image.jpg')

ori_img = original.copy()
img = cv2.cvtColor(ori_img, cv2.COLOR_BGR2GRAY)
img = cv2.GaussianBlur(img,(5,5),0)
_, thresh = cv2.threshold(img, 130, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for cnt in contours:
    [x, y, w, h] = cv2.boundingRect(cnt)
    if (w*h) >= 10000:
        box = cv2.minAreaRect(np.asarray(cnt))
        pts = cv2.boxPoints(box)
        pts = np.int0(pts)
cv2.drawContours(ori_img, [pts], 0, (0,255,0), 3)    
cv2.namedWindow('Frame', cv2.WINDOW_NORMAL)
cv2.imshow('Frame',ori_img)
k = cv2.waitKey(0)

簡短的回答:沒有

沒有 OpenCV 函數采用RotatedRect來限制它們正在處理的區域。

長答案:也許

某些 OpenCV 函數可以采用掩碼參數。 許多人沒有。

要從旋轉的矩形計算掩碼,請使用boxPoints ,然后將顏色為255的填充多邊形繪制到 dtype uint8和形狀(height, width)的數組中

mask = np.zeros((height, width), dtype=np.uint8)

# pts from boxPoints is a float32 array, fillPoly only likes integers
cv.fillPoly(
    img=mask,
    pts=np.round(pts).astype(np.int32).reshape((-1, 1, 2)), # round, cast, reshape into 2-channel column vector
    color=255)

更長的答案:做你的操作,然后使用掩碼復制回來。

source = ...
altered = your_operations(source)
source[mask != 0] = altered[mask != 0]

為了減少工作量,您也可以在子區域上進行操作(然后使用掩碼復制回來)。

暫無
暫無

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

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