-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfind_color_box
73 lines (54 loc) · 2.33 KB
/
find_color_box
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
71
72
73
import cv2
import numpy as np
from find_box_3 import resize
from shapedetector import ShapeDetector
def analyse_contours_using_shape(cnts,image,box_color):
sd = ShapeDetector()
for c in cnts:
area = cv2.contourArea(c)
shape = sd.detect(c)
if area > 100 and shape in ['rectangle','square']:
M = cv2.moments(c)
cX = int((M["m10"] / M["m00"]))
cY = int((M["m01"] / M["m00"]))
(x, y, w, h) = cv2.boundingRect(c)
cv2.putText(image, str(shape), (cX, cY-15), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
cv2.putText(image, str((cX,cY)), (cX, cY+15), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
cv2.drawContours(image, [c], -1, (255,255,255), 2)
cv2.rectangle(image, (x, y), (x + w, y + h), box_color, 2)
cv2.circle(image, (cX, cY), 2, (255, 255, 0), -1)
def analyse_contours_using_approx(cnts,image,box_color):
boxes = []
for c in cnts:
area = cv2.contourArea(c)
if area > 100:
epsilon = 0.1 * cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, epsilon, True)
if len(approx) >= 4:
M = cv2.moments(c)
cX = int((M["m10"] / M["m00"]))
cY = int((M["m01"] / M["m00"]))
(x, y, w, h) = cv2.boundingRect(c)
cv2.circle(image, (cX, cY), 2, (255, 0, 0), -1)
# cv2.drawContours(image, [approx], -1, (0,255,0), 2)
cv2.rectangle(image,(x,y),(x+w,y+h),box_color,2)
json = {'rectangle':(x, y, w, h),'centroid':(cX, cY)}
boxes.append(json)
# cv2.putText(image, str((cX,cY)), (cX, cY - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
return boxes
input_image = 'images/4.png'
image = cv2.imread(input_image)
image = resize(image)
# cv2.imshow('original',image)
roi = image
lower = np.array([50, 50, 50])
upper = np.array([250, 250, 250])
shapeMask = cv2.inRange(roi, lower, upper)
shapeMask = 255 - shapeMask
(cnts, _) = cv2.findContours(shapeMask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
blue = (200, 0, 0)
analyse_contours_using_shape(cnts,image,box_color=blue)
# analyse_contours_using_approx(cnts,image,box_color=blue)
cv2.imshow("processed Image", image)
cv2.imwrite('boxed.jpg',image)
cv2.waitKey()