我需要使用 python OpenCV 從這個矩形框中提取影像。

我已經看到并嘗試了幾種從形狀內部提取內容的方法,但每種方法都有局限性。大多數示例具有高對比度的純色形狀,例如綠色 (0,255,0) 或紅色 (255,0,0)。但是,我的問題是紅色框有一些透明度/不透明性,使得矩形的識別更加困難。矩形的紅色像素顏色范圍為 175-220,但影像的其余部分也具有相似的紅色色調,使得提取更加困難。

我對 OpenCV 相當陌生,因此非常感謝任何幫助。我已經在這個執行緒上嘗試了這兩種解決方案,但都沒有產生預期的結果。
uj5u.com熱心網友回復:
這是一個可能的解決方案:
- 將影像轉換為
HSV - 紅色閾值分割矩形
- 應用一些形態盡可能地閉合輪廓
- 檢測外部輪廓
- 根據面積過濾嘈雜的斑點;您正在尋找最大的輪廓
- 獲取輪廓的邊界矩形
- 使用邊界矩形對影像進行切片
讓我們看看代碼:
# imports:
import cv2
import numpy as np
# image path
path = "D://opencvImages//"
fileName = "uHNzL.jpg"
# Reading an image in default mode:
inputImage = cv2.imread(path fileName)
# Deep copy for results:
inputImageCopy = inputImage.copy()
# Convert the image to the HSV color space:
hsvImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2HSV)
# Set the HSV values:
lowRange = np.array([144, 105, 0])
uppRange = np.array([179, 255, 255])
# Create the HSV mask
binaryMask = cv2.inRange(hsvImage, lowRange, uppRange)
這是面具:
如您所見,矩形(大部分)在那里。讓我們嘗試用一些形態來改善輪廓。一些膨脹和腐蝕應該可以解決問題:
# Apply Dilate Erode:
kernel = np.ones((3, 3), np.uint8)
binaryMask = cv2.morphologyEx(binaryMask, cv2.MORPH_DILATE, kernel, iterations=3)
binaryMask = cv2.morphologyEx(binaryMask, cv2.MORPH_ERODE, kernel, iterations=3)
這是結果:
矩形稍微大一點,但噪音也是如此。但是,我們正在尋找最大的 blob,因此我們可以按區域過濾。讓我們裁剪最大的 blob:
# Find the target blobs on the binary mask:
contours, hierarchy = cv2.findContours(binaryMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Alright, just look for the outer bounding boxes:
for _, c in enumerate(contours):
# Get blob area:
blobArea = cv2.contourArea(c)
# Set minimum area:
minArea = 1000
if blobArea > minArea:
# Get the bounding rectangle:
boundRect = cv2.boundingRect(c)
# Bondary offset:
offset = 15
# Draw the rectangle on the input image:
# Get the dimensions of the bounding rect:
rectX = int(boundRect[0] offset)
rectY = int(boundRect[1] offset)
rectWidth = int(boundRect[2] - 2 * offset)
rectHeight = int(boundRect[3] - 2 * offset)
# Green Color, detected blobs:
color = (0, 255, 0)
cv2.rectangle(inputImageCopy, (int(rectX), int(rectY)),
(int(rectX rectWidth), int(rectY rectHeight)), color, 2)
# Crop contour:
croppedImage = inputImage[rectY:rectY rectHeight, rectX:rectX rectWidth]
cv2.imshow("croppedImage", croppedImage)
cv2.waitKey(0)
cv2.imshow("Rectangles", inputImageCopy)
cv2.waitKey(0)
現在,因為我們正在處理變形影像,矩形二進制輪廓比實際的紅色矩形要大一點,所以我引入了一個偏移量來將影像裁剪得更緊一點。
這是具有15像素偏移的邊界矩形:
這是裁剪后的影像:
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/511473.html
標籤:Pythonopencv
