@Dtractus . Sorry for delay. I had to do some work in my backyard.. I modified your code. Somehow you don't needed this if w>50 and h>50:
. This may occurred problem.
#!/usr/bin/python 37
#OpenCV 4.3.0, Raspberry Pi 3/B/4B-w/4/8GB RAM, Buster,v10.
#Date: 3rd, June, 2020
import cv2
# Load the image
img = cv2.imread('photos/testtt.png')
# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(img, 170, 490)
# Apply adaptive threshold
thresh = cv2.adaptiveThreshold(edged, 255, 1, 1, 11, 2)
thresh_color = cv2.cvtColor(thresh, cv2.COLOR_GRAY2BGR)
# apply some dilation and erosion to join the gaps - change iteration to detect more or less area's
thresh = cv2.dilate(thresh,None,iterations = 15)
thresh = cv2.erode(thresh,None,iterations = 15)
# Find the contours
contours,hierarchy = cv2.findContours(thresh,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
# For each contour, find the bounding rectangle and draw it
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img,
(x,y),(x+w,y+h),
(0,255,0),
2)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
As I noticed that you have 2 rectangles on image. I cant go further, because I haven't research on OpenCV 4 yet.
Here is code:
#!/usr/bin/python 37
#OpenCV 4.3.0, Raspberry Pi 3/B/4B-w/4/8GB RAM, Buster,v10.
#Date: 5th, June, 2020
import cv2
# read and scale down image
img = cv2.pyrDown(cv2.imread('text3.jpg', cv2.IMREAD_UNCHANGED))
# threshold image
ret, threshed_img = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),
11, 55, cv2.THRESH_BINARY)
thresh = cv2.dilate(threshed_img, None, iterations = 5)
thresh = cv2.erode(threshed_img, None, iterations = 5)
contours, hier = cv2.findContours(thresh,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
# get the bounding rect
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), thickness=1, lineType=8, shift=0)
cv2.imshow('contours', img)
while(cv2.waitKey()is not ord('q')):
continue
cv2.destroyAllWindows()
Output:
You are missing
cv2.rectangle
or probablycv2.DrawContours
@supra56 , thanks but when i use drawContours, draws the outer rectangle of the image. it does not detect rectangles inside.
You don't needed to do that. Just leave it out.