[英]How I can detect irregular shapes and remove from image with opencv?
我在 Python 中使用 opencv 庫,我遇到了這個問題。 我有這張圖片,我之前去除了很多噪點,但是在這張圖片中有很多不規則的形狀我想去除。
例如 :
我使用這張圖片:
為了獲取起始圖像,我使用以下代碼:
import cv2
image = cv2.imread("Image.png")
## Heading ##
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))
inverted_thresh = 255 - thresh
dilate = cv2.dilate(inverted_thresh, kernel, iterations=3)
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x, y, w, h = cv2.boundingRect(c)
ROI = thresh[y:y + h, x:x + w]
data = pytesseract.image_to_string(ROI, lang='eng', config='--psm 6').lower()
sub = cv2.subtract(~gray, dilate)
# In[4]:
# Sobel Edge Detection
sobelx = cv2.Sobel(src=sub, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=5) # Sobel Edge Detection on the X axis
sobely = cv2.Sobel(src=sub, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=5) # Sobel Edge Detection on the Y axis
sobelxy = cv2.Sobel(src=sub, ddepth=cv2.CV_64F, dx=1, dy=1, ksize=5) # Combined X and Y Sobel Edge Detection
# In[8]:
# Canny Edge Detection
edges = cv2.Canny(image=sub, threshold1=45, threshold2=55) # Display Canny Edge Detection Image
cv2.imshow('Canny Edge Detection', edges)
我會得到這個結果
我怎樣才能得到這個結果?
如果您知道邊界的最小線長,則可以輕松過濾其他元素。
import cv2
gray = cv2.imread("Image.png", cv2.IMREAD_GRAYSCALE)
minLineWidth = 397
hKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (minLineWidth, 1))
vKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, minLineWidth))
hGray = cv2.morphologyEx(gray, cv2.MORPH_OPEN, hKernel)
vGray = cv2.morphologyEx(gray, cv2.MORPH_OPEN, vKernel)
gray = cv2.bitwise_or(hGray, vGray)
cv2.imshow("gray", gray)
cv2.waitKey()
如果您不知道最小線長,可以使用概率霍夫變換來查找所有線。 然后您可以按角度過濾線條並找到最小重復線條長度。 在您可以應用建議的代碼或僅繪制過濾線之后。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.