Skip to content

Commit ff5dfa4

Browse files
committed
Create segmentation2.py
1 parent 5fdbd53 commit ff5dfa4

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

ch5/segmentation2.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import cv2
2+
import numpy as np
3+
4+
# Load the image
5+
img = cv2.imread('plate_straight.png')
6+
7+
# convert to grayscale
8+
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
9+
10+
# smooth the image to avoid noises
11+
gray = cv2.medianBlur(gray,5)
12+
13+
# Apply adaptive threshold
14+
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
15+
thresh_color = cv2.cvtColor(thresh,cv2.COLOR_GRAY2BGR)
16+
17+
# apply some dilation and erosion to join the gaps
18+
thresh = cv2.dilate(thresh,None,iterations = 3)
19+
thresh = cv2.erode(thresh,None,iterations = 2)
20+
21+
# Find the contours
22+
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
23+
24+
# For each contour, find the bounding rectangle and draw it
25+
for cnt in contours:
26+
x,y,w,h = cv2.boundingRect(cnt)
27+
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
28+
cv2.rectangle(thresh_color,(x,y),(x+w,y+h),(0,255,0),2)
29+
30+
# Finally show the image
31+
cv2.imshow('img',img)
32+
cv2.imshow('res',thresh_color)
33+
cv2.waitKey(0)
34+
cv2.destroyAllWindows()

0 commit comments

Comments
 (0)