我是 OpenCV 的新手。正如您在下面的代碼中所見,我有一張已經處理過的郵票的“簡單”影像。現在我遇到了裁剪影像以獲得印章的問題。邊緣上的點和條紋會干擾我當前識別郵票的代碼。影像可能不同,因此無法修復影像的位置。
代碼:
img = cv2.imread('./images/image.JPG')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_blur = cv2.GaussianBlur(img_gray, (3,3), 0)
edges = cv2.Canny(image=img_blur, threshold1=100, threshold2=200)


真實影像


uj5u.com熱心網友回復:
這是一個簡單的方法:
獲取二值影像。我們加載影像,轉換為灰度,高斯模糊,然后Otsu的閾值得到二值影像。
去除小的偽影和噪音。創建一個矩形結構元素并變形打開以去除少量噪音。然后變形關閉以將單個輪廓組合成單個輪廓,假設印章是單個輪廓。
檢測和提取標記 ROI。查找輪廓,使用輪廓區域和形狀近似進行過濾。這個想法是,如果一個輪廓有四個頂點,那么它就是一個正方形。我們可以使用 Numpy 切片提取圖章 ROI 并保存圖章
提取的 ROI 結果
這是評論中其他兩個輸入影像的結果。假設對于每張影像,只有一個印章或一組相鄰的印章。對于這些情況,我們按輪廓區域排序,并假設最大的輪廓是印章。


代碼
import cv2
# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.jpg")
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY cv2.THRESH_OTSU)[1]
# Morph operations to remove small artifacts and noise
open_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, open_kernel, iterations=1)
close_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7,7))
close = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, close_kernel, iterations=2)
# Find contours, filter using contour area, and shape approximation
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
for c in cnts:
peri = cv2.arcLength(c, True)
area = cv2.contourArea(c)
approx = cv2.approxPolyDP(c, 0.05 * peri, True)
# Assumption is if the contour has 4 vertices then its a square shape
# 2nd assumption is that there's only one stamp, or one group of stamps
if len(approx) == 4 and area > 100:
x,y,w,h = cv2.boundingRect(approx)
ROI = original[y:y h, x:x w]
cv2.imshow("ROI", ROI)
cv2.imwrite("ROI.png", ROI)
break
cv2.waitKey()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466812.html
標籤:Python 图片 opencv 图像处理 计算机视觉
上一篇:填充ROI的中心
