forked from lforet/cad_vision
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget_contour.py
242 lines (201 loc) · 11.3 KB
/
get_contour.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/bin/env python
__version__ = '.01'
__author__ = 'Laird Foret ([email protected])'
__copyright__ = '(C) 2015. GNU GPL 3.'
"""
#returns SVG of contour of object of a given image
"""
import cv2
import sys
import numpy as np
import time
import imghdr
import os
import colorsys
import uuid
IMAGE_X = 640
IMAGE_Y = 480
def auto_canny(image, sigma=0.5):
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
print >> sys.stderr, "[get_contour] saved canny_img.bmp"
cv2.imwrite("canny_img.bmp", edged)
# return the edged image
return edged
def get_contour(Img_PathandFilename = 'temp_image_file', resize_dim=(IMAGE_X,IMAGE_Y) ):
#returns SVG of contour of object of a given image
try:
img = cv2.imread(Img_PathandFilename)
except:
print >> sys.stderr, "******* Could not open image file *******"
print >> sys.stderr, "Unexpected error:", sys.exc_info()[0]
sys.exit(-1)
#resize image
resized_img = cv2.resize(img, resize_dim, interpolation = cv2.INTER_AREA)
print >> sys.stderr, "[get_contour] resized image to:", resize_dim
#apply canny
edges = cv2.cvtColor(resized_img, cv2.COLOR_BGR2GRAY)
#edges = cv2.GaussianBlur(edges, (3,3), 0)
#edges = auto_canny(edges)
#this line below is what worked in production
edges = cv2.Canny(edges,30,180)
#ret,edges = cv2.threshold(edges, 127,255,cv2.THRESH_BINARY)
#edges = cv2.GaussianBlur(edges, (5,5), 0)
#despeckle image
kernel = np.ones((5,5),np.uint8)
#this line below is how "fat" or loose the object will fit in the foam
edges = cv2.dilate(edges,kernel,iterations = 2)
edges = cv2.erode(edges,kernel,iterations = 1)
#BLUR THE IMAGE a bit
#blurr = (3,3)
#edges = cv2.blur(edges,blurr)
#cv2.imwrite('blurred_image.jpg', edges)
#print >> sys.stderr, "[ImageReceiver] blurred image:", blurr
#find contours
contours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
print >> sys.stderr, "[get_contour] Contours found:", len(contours)
#import inspect
#print >> sys.stderr, (inspect.getsourcefile(enumerate))
#get areas of contours and sort them from greatest to smallest
areaArray= []
for i, c in enumerate(contours):
area = cv2.contourArea(c)
areaArray.append(area)
#first sort the array by area
sorted_areas = sorted(zip(areaArray, contours), key=lambda x: x[0], reverse=True)
#find the nth largest contour [n-1][1], in this case 2
#in this case return largest
item_contour = sorted_areas[0][1]
contour_size = cv2.minAreaRect(item_contour)
print >> sys.stderr, "[get_contour] Contour size", contour_size
center_of_contour = [int(contour_size[0][0]),int(contour_size[0][1])]
print center_of_contour
print >> sys.stderr, "[get_contour] Contour center", center_of_contour
contour_width = int(contour_size[1][0] )
contour_height = int(contour_size[1][1] )
print "contour_width;", contour_width
print "contour_height:", contour_height
scaling_factor = 1.0
if contour_width > contour_height:
print "contour_width is bigger"
scaling_factor = scaling_factor + (1.0-(contour_width / IMAGE_X))
else:
print "contour_height is bigger"
scaling_factor = scaling_factor + (1.0-(contour_height / IMAGE_Y))
print "scaling_factor", scaling_factor
#create a blank image
#contour_image = np.zeros((resize_dim[1], resize_dim[0], 3), np.uint8)
contour_image = np.zeros(((resize_dim[1]*scaling_factor), scaling_factor*resize_dim[0], 3), np.uint8)
#draw contour on blank image (fill in)
#perimeter = cv2.arcLength(item_contour,True)
#print "perimeter:", perimeter
#scaling_factor = 1.0
resized_contour = scaling_factor*np.array(item_contour)
resized_contour = resized_contour.astype(int)
print item_contour[0], resized_contour[0]
cv2.drawContours(contour_image, [resized_contour], -1, (255, 255, 255), -1)
leftmost = tuple(resized_contour[resized_contour[:,:,0].argmin()][0])
rightmost = tuple(resized_contour[resized_contour[:,:,0].argmax()][0])
topmost = tuple(resized_contour[resized_contour[:,:,1].argmin()][0])
bottommost = tuple(resized_contour[resized_contour[:,:,1].argmax()][0])
#print "leftmost", leftmost
#print "rightmost", rightmost
#print "topmost", topmost
#print "bottommost", bottommost
#crop image to make object touch edges
contour_image = contour_image[topmost[1]:bottommost[1], leftmost[0]:rightmost[0]]
#Smooth rough edges
#contour_image = cv2.GaussianBlur(contour_image, (5,5), 0)
contour_image = cv2.dilate(contour_image,kernel,iterations = 2)
contour_image = cv2.erode(contour_image ,kernel,iterations = 1)
#invert image
contour_image = np.invert(contour_image)
#for now just save contour image
contour_image_filename = str(uuid.uuid1())+'.bmp'
cv2.imwrite(contour_image_filename, contour_image )
#call potrace to convert to SVG
command = "potrace --svg -k 0.1 "+contour_image_filename+" -o object_contour.svg"
os.system(command)
#remove temp image file
command = 'rm ' + contour_image_filename
os.system(command)
print >> sys.stderr, "[get_contour] saved contour image:", contour_image_filename
SVG_to_return = cv2.imread('object_contour.svg')
#contours_to_return = np.reshape(item_contour, (640,2))
contours_to_return = item_contour
return SVG_to_return
if __name__=="__main__":
if len(sys.argv) > 1:
get_contour(sys.argv[1])
else:
print >> sys.stderr, "Usage: python get_contour.py 'path/imagefile_to_process'"
sys.exit(-1)
'''Code below not used
def rgb2hsv(rgb):
return scale_hsv( colorsys.rgb_to_hsv(norm(rgb[0]), norm(rgb[1]), norm(rgb[2])) )
def norm( x):
return (x/255.0)
def scale_hsv( hsv):
return ([(hsv[0]*180),(hsv[1]*255),(hsv[2]*255)])
def remove_background(img, roi_size, bg_percent):
#get samples from the 4 corners of the picture
#this will be assumed to be background colors.
#taking the average of this color, remove all similar (within percentage) color from picture
if roi_size == None: roi_size = 25
if bg_percent == None: bg_percent = 0.05
topl = img[ 0:roi_size, 0:roi_size ]
topr = img[0:roi_size , (img.shape[1]-roi_size ):img.shape[1]]
bottom_l = img[(img.shape[0]-roi_size ):img.shape[0], 0:roi_size ]
bottom_r = img[(img.shape[0]-roi_size ):img.shape[0], (img.shape[1]-roi_size ):img.shape[1]]
#get avg color
avg_bg_color_RGB = np.mean(np.array([cv2.mean(topl), cv2.mean(topr), cv2.mean(bottom_l), cv2.mean(bottom_r)]).astype(int), axis=0)
#avg_bg_color = np.rint([avg_bg_color[0], avg_bg_color[1], avg_bg_color[2]]
R_lower = int(avg_bg_color_RGB[0] - (avg_bg_color_RGB[0] * bg_percent))
if R_lower < 0: R_lower = 0
R_upper = int(avg_bg_color_RGB[0] + (avg_bg_color_RGB[0] * bg_percent))
if R_upper >255: R_upper = 255
G_lower = int(avg_bg_color_RGB[1] - (avg_bg_color_RGB[1] * bg_percent))
if G_lower < 0: G_lower = 0
G_upper = int(avg_bg_color_RGB[1] + (avg_bg_color_RGB[1] * bg_percent))
if G_upper >255: G_upper = 255
B_lower = int(avg_bg_color_RGB[2] - (avg_bg_color_RGB[2] * bg_percent))
if B_lower < 0: B_lower = 0
B_upper = int(avg_bg_color_RGB[2] + (avg_bg_color_RGB[2] * bg_percent))
if B_upper >255: B_upper = 255
lower_RGB = np.array([R_lower, G_lower, B_lower])
upper_RGB = np.array([R_upper, G_upper, B_upper])
lower_HSV = np.array(rgb2hsv([R_lower, G_lower, B_lower]))
upper_HSV = np.array(rgb2hsv([R_upper, G_upper, B_upper]))
#lower_HSV = np.array([20,0,0])
upper_HSV = np.array([180,255,255])
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# lower mask
mask0 = cv2.inRange(img, lower_RGB, upper_RGB)
print >> sys.stderr, "avg_bg_color_RGB:", avg_bg_color_RGB
print >> sys.stderr, 'RGB_lower:', R_lower, G_lower, B_lower
print >> sys.stderr, 'RGB_upper:', R_upper, G_upper, B_upper
print >> sys.stderr, 'lower_HSV:', lower_HSV
print >> sys.stderr, 'upper_HSV:', upper_HSV
print >> sys.stderr, 'mask0:', mask0.shape
# upper mask (170-180)
#lower_red = np.array([170,50,50])
#upper_red = np.array([180,255,255])
#mask1 = cv2.inRange(img_hsv, lower_red, upper_red)
# set my output img to zero everywhere except my mask
#output_img = img.copy()
#output_img[np.where(mask==0)] = 0
# or your HSV image, which I *believe* is what you want
output_hsv = img.copy()
output_hsv[np.where(mask0==0)] = 0
#output_hsv = cv2.bitwise_and(img,img, mask= mask0)
output_rgb = cv2.cvtColor(output_hsv, cv2.COLOR_HSV2RGB)
cv2.imwrite('background_mask.jpg', mask0)
cv2.imwrite('background_removed.jpg', output_hsv)
cv2.imwrite('image_HSV.jpg', img_hsv)
# convert to hsv and find range of colors
#hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
'''