forked from hrehfeld/2019-09-hackathon-pforzheim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmustis_version.py
70 lines (53 loc) · 1.87 KB
/
mustis_version.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Import the Libraries
import numpy as np
import cv2
import random
import sys
# load the image
#import os
#desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')
#path = desktop+'/test2.jpg'
path = sys.argv[1]
# Reading Image
img = cv2.imread(path, 1)
# See how it looks
cv2.imshow("Original", img)
# Converting the image to Gray Scale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Removing Gaussian Noise
blur = cv2.GaussianBlur(gray, (3, 3), 0)
# Applying inverse binary due to white background and adapting thresholding for better results
thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 205, 1)
# Checking to see how it looks
cv2.imshow("Binary", thresh)
# Finding contours with simple retrieval (no hierarchy) and simple/compressed end points
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# Checking to see how many contours were found
print(len(contours))
# An empty list to store filtered contours
filtered = []
# Looping over all found contours
for c in contours:
# If it has significant area, add to list
if cv2.contourArea(c) < 1000: continue
filtered.append(c)
# Checking the number of filtered contours
print(len(filtered))
# Initialize an equally shaped image
objects = np.zeros([img.shape[0], img.shape[1], 3], 'uint8')
# Looping over filtered contours
for c in filtered:
# Select a random color to draw the contour
col = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
# Draw the contour on the image with above color
cv2.drawContours(objects, [c], -1, col, -1)
# Fetch contour area
area = cv2.contourArea(c)
# Fetch the perimeter
p = cv2.arcLength(c, True)
print(area, p)
# Finally show the processed image
cv2.imshow("Contours", objects)
# Closing protocol
cv2.waitKey(0)
cv2.destroyAllWindows()