Reputation: 61
I am having some problem with removing unwanted contours.
Image with detected contours:
I do not want the following contours as shown in this image (the area marked in blue color):
But I cannot seem to get rid of them. My code:
img = cv2.imread(img_path)
edges = cv2.Canny(img, 240, 240)
#cv2.imshow('', edges)
thresh = cv2.threshold(edges,150, 255,cv2.THRESH_BINARY_INV)[1]
cnts, h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Show and Write Threshold Image
#cv2.imshow('thresh', thresh)
#cv2.imwrite('Thresholded_labeled_image.jpg', thresh)
# Find and Draw Contours
contours, h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
img_contours = cv2.drawContours(thresh, contours, -1, (0,255,0), 3)
cv2.imshow('contours', img_contours)
# Remove Noise
kernel = np.ones((5,5),np.float32)/25
dst = cv2.filter2D(img_contours,-1,kernel)
plt.subplot(121),plt.imshow(img_contours),plt.title('Image_Contours')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(dst),plt.title('Averaging')
plt.xticks([]), plt.yticks([])
plt.show()
I tried morphology:
kernel = np.ones((5,5),np.uint8)
closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
cv2.imshow('closing', closing)
I tried changing the size of the kernels but it still doesn't work. I still see those unwanted contours.
Is there anything I could try to do?
Edit 1: Using boundingRect
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4,2))
dilate = cv2.dilate(thresh, kernel, iterations=2)
# Find contours, highlight text areas, and extract ROIs
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
ROI_number = 0
ROI_images = []
for c in cnts:
area = cv2.contourArea(c)
print("Area is: ", area)
x,y,w,h = cv2.boundingRect(c)
print("Height: ", h)
if area > 100 and 0<h<300:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 3)
ROI = img[y:y+h, x:x+w]
# cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
ROI_number += 1
ROI_images.append(ROI)
Output:
Upvotes: 0
Views: 262
Reputation: 13349
This is how you do. You have to edit the below code as per your requirement.
import cv2
import numpy as np
img = cv2.imread('try.png')
img_res = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,1)
contours,h = cv2.findContours(thresh,1,2)
# area_list = []
for cnt in contours:
area = cv2.contourArea(cnt)
x,y,w,h = cv2.boundingRect(cnt)
# print(area,w,h)
if area<5200:
img[y:y+h, x:x+w] = (255,255,255)
cv2.rectangle(img_res, (x, y), (x + w, y + h), (0, 255, 0), 3)
try.png:
(Here I have loaded it as RGB image, you have to modify your code to find out the contours)
img_res:
img:
Upvotes: 1