def pixeles(imagen): global pixel_rojo, pixel_azul, pixel_verde rojo = cv.CreateImage(cv.GetSize(imagen),cv.IPL_DEPTH_8U,1) verde = cv.CreateImage(cv.GetSize(imagen),cv.IPL_DEPTH_8U,1) azul = cv.CreateImage(cv.GetSize(imagen),cv.IPL_DEPTH_8U,1) cv.InRangeS(imagen,(pixel_rojo[0]-tolerancia,pixel_rojo[1]-tolerancia,pixel_rojo[2]-tolerancia),(pixel_rojo[0]+tolerancia,pixel_rojo[1]+tolerancia,pixel_rojo[2]+tolerancia),rojo) cv.InRangeS(imagen,(pixel_verde[0]-tolerancia,pixel_verde[1]-tolerancia,pixel_verde[2]-tolerancia),(pixel_verde[0]+tolerancia,pixel_verde[1]+tolerancia,pixel_verde[2]+tolerancia),verde) cv.InRangeS(imagen,(pixel_azul[0]-tolerancia,pixel_azul[1]-tolerancia,pixel_azul[2]-tolerancia),(pixel_azul[0]+tolerancia,pixel_azul[1]+tolerancia,pixel_azul[2]+tolerancia),azul) p_red = p_green = p_blue = 0 for j in range(1,imagen.height,1): for i in range(1,imagen.width,1): green = cv.Get2D(verde,j,i) red = cv.Get2D(rojo ,j,i) blue = cv.Get2D(azul ,j,i) if blue[0] == 255: p_blue = 1 if green[0] == 255: p_green = 1 if red[0] == 255: p_red = 1 print p_red, p_green, p_blue
def createSpline(image, channel=0, camera_angle=45, top_crop=0, bottom_crop=0, rotation_center=0, upper_threshold=255, lower_threshold=0): spline = [0] * image.height #Sanity check some of the inputs rotation_center = image.width / 2 bottom_crop = image.height - 1 - bottom_crop if bottom_crop == top_crop or top_crop > bottom_crop: print "Error, the bottom crop value is less or equal to the top crop value" return #grab the spline for y in range(top_crop, bottom_crop): max_value = 0 max_position = 0 for x in range(image.width - 1): pixel = cv.Get2D(image, y, x) if pixel[channel] > max_value and pixel[ channel] < upper_threshold and pixel[ channel] > lower_threshold: max_value = pixel[channel] max_position = x spline[y] = max_position #fill in any holes good_top = rotation_center good_bottom = rotation_center for y in range(len(spline) - 1): #find any points that area too large or small if spline[y] == 0 or spline[y] == image.width: #find the next good point for z in range(y, len(spline) - 1): if spline[z] > 0 and spline[z] < image.width: good_bottom = spline[z] break #set the bad point to the avearage of the two nearest good points (not perfect, but close enough) spline[y] = (good_top + good_bottom) / 2 good_top = spline[y] colorspline = [(0, 0, 0)] * len(spline) #grab the color spline for y in range(len(spline) - 1): colorspline[y + top_crop] = cv.Get2D(image, y, spline[y]) #remove center offset for y in range(len(spline) - 1): spline[y] = spline[y] - rotation_center #Package the result up in a Spline class result = Spline() result.spline = spline result.colorspline = colorspline return result
def change_by_hue(self): for x in range(self.threshold.width): for y in range(self.threshold.height): if cv.Get2D(self.threshold, y, x)[0] == 255: val = cv.Get2D(self.hsv, y, x) cv.Set2D(self.hsv, y, x, (self.hue, val[1], val[2])) cv.CvtColor(self.hsv, self.image_color, cv.CV_HSV2BGR)
def blurry_histogram(im, num_samples=300, offset=1): im = image.rgb2gray(im) size = cv.GetSize(im) used = set([]) i = 0 diffs = {} while i < num_samples: # we can't use the first row of pixels x = random.randrange(0, size[0]) y = random.randrange(offset, size[1]) if (x, y) not in used: pixel1 = cv.Get2D(im, y, x) pixel2 = cv.Get2D(im, y - offset, x) diff = tuple(map(lambda a, b: a - b, pixel1, pixel2)) if diff not in diffs: diffs[diff] = 0 diffs[diff] += 1 used = used.union([(x, y)]) i += 1 max_i = max_v = 0 second_max_i = second_max_v = 0 for key, val in diffs.iteritems(): if max_v < val: second_max_i, second_max_v = max_i, max_v max_v, max_i = val, key return (max_v - second_max_v) / abs(max_i[0] - second_max_i[0])
def compute_glcm(img, d): order = 8 newimg = quantize(img, order) glcm = cv.CreateMat(order,order,cv.CV_8UC1) normglcm = cv.CreateMat(order, order, cv.CV_32FC1) cv.SetZero(glcm) div = 255/order for i in range(img.rows-d): for j in range(img.cols-d): val1 = cv.Get2D(newimg, i, j) val2 = cv.Get2D(newimg, i+d, j+d) p = int(val1[0]/div) q = int(val2[0]/div) if p>=order: p = order -1 if q>=order: q = order -1 #print p, q val3 = cv.Get2D(glcm, p, q) cv.Set2D(glcm, p, q, (val3[0]+1)) tot = cv.Sum(glcm) for i in range(glcm.rows): for j in range(glcm.cols): val3 = cv.Get2D(glcm, i , j) val = 1.0*val3[0]/tot[0] cv.Set2D(normglcm, i, j, (val)) #print round(float(cv.Get2D(normglcm, i, j)[0]), 3), #print "\n" return normglcm
def determineMarkerOrientation(self, frame): (xm, ym) = self.lastMarkerLocation realval = cv.Get2D(self.frameReal, ym, xm)[0] imagval = cv.Get2D(self.frameImag, ym, xm)[0] self.orientation = (math.atan2(-realval, imagval) - math.pi / 2) / self.order maxValue = 0 maxOrient = 0 searchDist = self.kernelSize / 3 for k in range(self.order): orient = self.orientation + 2 * k * math.pi / self.order xm2 = int(xm + searchDist * math.cos(orient)) ym2 = int(ym + searchDist * math.sin(orient)) if (xm2 > 0 and ym2 > 0 and xm2 < frame.width and ym2 < frame.height): try: intensity = cv.Get2D(frame, ym2, xm2) if (intensity[0] > maxValue): maxValue = intensity[0] maxOrient = orient except: print("determineMarkerOrientation: error: %d %d %d %d" % (ym2, xm2, frame.width, frame.height)) pass self.orientation = self.limitAngleToRange(maxOrient)
def read_train_model(): #载入data arrTemp = randn(4) arrGonglin = randn(150, 164, 164, 3) arrQinxuebin = randn(150, 164, 164, 3) arrSunming = randn(150, 164, 164, 3) arrLvyuanjie = randn(150, 164, 164, 3) arrGonglin = np.asarray(arrGonglin, dtype=np.float32) arrQinxuebin = np.asarray(arrQinxuebin, dtype=np.float32) arrSunming = np.asarray(arrSunming, dtype=np.float32) arrLvyuanjie = np.asarray(arrLvyuanjie, dtype=np.float32) for i in range(150): #164x164 print i imgGonglin = cv.LoadImage( "/home/deeplearn/Desktop/qin/gonglin/" + str(i) + ".jpg", 1) imgQinxuebin = cv.LoadImage( "/home/deeplearn/Desktop/qin/qinxuebin/" + str(i) + ".jpg", 1) imgSunming = cv.LoadImage( "/home/deeplearn/Desktop/qin/sunming/" + str(i) + ".jpg", 1) imgLvyuanjie = cv.LoadImage( "/home/deeplearn/Desktop/qin/sunming/" + str(i) + ".jpg", 1) for h in range(164): for w in range(164): pixPair = cv.Get2D(imgGonglin, h, w) arrTemp = np.array(pixPair) arrGonglin[i, w, h, 0] = arrTemp[0] arrGonglin[i, w, h, 1] = arrTemp[1] arrGonglin[i, w, h, 2] = arrTemp[2] pixHorse = cv.Get2D(imgQinxuebin, h, w) arrTemp = np.array(pixHorse) arrQinxuebin[i, w, h, 0] = arrTemp[0] arrQinxuebin[i, w, h, 1] = arrTemp[1] arrQinxuebin[i, w, h, 2] = arrTemp[2] pixCat = cv.Get2D(imgSunming, h, w) arrTemp = np.array(pixCat) arrSunming[i, w, h, 0] = arrTemp[0] arrSunming[i, w, h, 1] = arrTemp[1] arrSunming[i, w, h, 2] = arrTemp[2] pixCat = cv.Get2D(imgLvyuanjie, h, w) arrTemp = np.array(pixCat) arrLvyuanjie[i, w, h, 0] = arrTemp[0] arrLvyuanjie[i, w, h, 1] = arrTemp[1] arrLvyuanjie[i, w, h, 2] = arrTemp[2] #cv.Zero(imgPair) #cv.Zero(imgHorse) #cv.Zero(imgCat) print "Load data finished!" zeroArray = np.zeros((4, 4)) for nI in range(0, 4): zeroArray[nI][nI] = 1 print zeroArray return arrGonglin, arrQinxuebin, arrSunming, arrLvyuanjie, zeroArray
def reconocimiento_robot_pos (imagen): tolerancia = 30 cv.ShowImage('Prueba',imagen) verde = cv.CreateImage(cv.GetSize(imagen),cv.IPL_DEPTH_8U,1) azul = cv.CreateImage(cv.GetSize(imagen),cv.IPL_DEPTH_8U,1) amarillo = cv.CreateImage(cv.GetSize(imagen),cv.IPL_DEPTH_8U,1) pixel_verde = [76,177,34] pixel_azul = [232,162,0] pixel_amarillo = [164,73,163] cv.InRangeS(imagen,(pixel_verde[0]-tolerancia,pixel_verde[1]-tolerancia,pixel_verde[2]-tolerancia),(pixel_verde[0]+tolerancia,pixel_verde[1]+tolerancia,pixel_verde[2]+tolerancia),verde) cv.InRangeS(imagen,(pixel_azul[0]-tolerancia,pixel_azul[1]-tolerancia,pixel_azul[2]-tolerancia),(pixel_azul[0]+tolerancia,pixel_azul[1]+tolerancia,pixel_azul[2]+tolerancia),azul) cv.InRangeS(imagen,(pixel_amarillo[0]-tolerancia,pixel_amarillo[1]-tolerancia,pixel_amarillo[2]-tolerancia),(pixel_amarillo[0]+tolerancia,pixel_amarillo[1]+tolerancia,pixel_amarillo[2]+tolerancia),amarillo) cv.ShowImage('Color Verde' ,verde) cv.ShowImage('Color Azul' ,azul) cv.ShowImage('Color Amarillo' ,amarillo) (cg, ca, cy) = ([],[],[]) sumx_g = sumy_g = sumx_a = sumy_a = sumx_y = sumy_y = 0 for j in range(1,480,1): for i in range(1,640,1): a = cv.Get2D(azul ,j,i) v = cv.Get2D(verde,j,i) y = cv.Get2D(amarillo,j,i) if v[0] == 255: cg += [(i,j)] sumx_g = sumx_g + i sumy_g = sumy_g + j if a[0] == 255: ca += [(i,j)] sumx_a = sumx_a + i sumy_a = sumy_a + j if y[0] == 255: cy += [(i,j)] sumx_y = sumx_y + i sumy_y = sumy_y + j p_old1_x = i p_old1_y = j ro_x = sumx_g/len(cg) #0 ro_y = sumy_g/len(cg) rf_x = sumx_a/len(ca) rf_y = sumy_a/len(ca) rb_x = sumx_y/len(cy) rb_y = sumy_y/len(cy) return ro_x,ro_y,rf_x,rf_y,rb_x,rb_y
def change_by_rgb(self): avgs = self.get_avgs(self.image_color) for x in range(self.threshold.width): for y in range(self.threshold.height): if cv.Get2D(self.threshold, y, x)[0] == 255: val = cv.Get2D(self.image_color, y, x) difs = (val[2] - avgs[0], val[1] - avgs[1], val[0] - avgs[2]) cv.Set2D(self.image_color, y, x, (self.new_color[2] + difs[2], self.new_color[1] + difs[1], self.new_color[0] + difs[0], 0))
def my_mouse_callback(event, x, y, flags, param): global evente, h, s, v, i, r, g, b, j evente = event if event == cv.CV_EVENT_LBUTTONDBLCLK: # Here event is left mouse button double-clicked hsv = cv.CreateImage(cv.GetSize(frame), 8, 3) cv.CvtColor(frame, hsv, cv.CV_BGR2HSV) (h, s, v, i) = cv.Get2D(hsv, y, x) (r, g, b, j) = cv.Get2D(frame, y, x) print "x,y =", x, y print "hsv= ", cv.Get2D(hsv, y, x) # Gives you HSV at clicked point print "im= ", cv.Get2D(frame, y, x) # Gives you RGB at clicked point
def get_avgs(self, image): c = 0 s = (0, 0, 0) for x in range(image.width): for y in range(image.height): if cv.Get2D(self.threshold, y, x)[0] == 255: vals = cv.Get2D(image, y, x) s = (s[0] + vals[0], s[1] + vals[1], s[2] + vals[2]) c += 1 s = (s[0] / c, s[1] / c, s[2] / c) print "returning averages: ", s return s
def reconocimiento_robot_pos (): global pixel_azul, pixel_verde , width , height peq_imagen, imagen = imagen_homografia(1) tolerancia = 30 verde = cv.CreateImage(cv.GetSize(imagen),cv.IPL_DEPTH_8U,1) azul = cv.CreateImage(cv.GetSize(imagen),cv.IPL_DEPTH_8U,1) cv.InRangeS(imagen,(pixel_verde[0]-tolerancia,pixel_verde[1]-tolerancia,pixel_verde[2]-tolerancia),(pixel_verde[0]+tolerancia,pixel_verde[1]+tolerancia,pixel_verde[2]+tolerancia),verde) cv.InRangeS(imagen,(pixel_azul[0]-tolerancia,pixel_azul[1]-tolerancia,pixel_azul[2]-tolerancia),(pixel_azul[0]+tolerancia,pixel_azul[1]+tolerancia,pixel_azul[2]+tolerancia),azul) (cg, cb, cy) = ([],[],[]) sumx_g = sumy_g = sumx_b = sumy_b = sumx_y = sumy_y = 0 for j in range(1,height,1): for i in range(1,width,1): b = cv.Get2D(azul ,j,i) g = cv.Get2D(verde,j,i) if g[0] == 255: cg += [(i,j)] sumx_g = sumx_g + i sumy_g = sumy_g + j if b[0] == 255: cb += [(i,j)] sumx_b = sumx_b + i sumy_b = sumy_b + j p_old1_x = i p_old1_y = j ro_x = sumx_g/len(cg) ro_y = sumy_g/len(cg) rf_x = sumx_b/len(cb) rf_y = sumy_b/len(cb) alt_real_tripode = alt_tripode - (float(dist_trip_cancha*alt_tripode)/float(dist_trip_cancha+largo_cancha)) corr_ro_y = float(ro_y) + (float(ro_y * alt_robot) / float(alt_real_tripode)) corr_rf_y = float(rf_y) + (float(rf_y * alt_robot) / float(alt_real_tripode)) if ro_x > width/2 : corr_ro_x = float(ro_x) - (float(ro_x * alt_robot) / float(alt_real_tripode)) else: corr_ro_x = float(ro_x) + (float(ro_x * alt_robot) / float(alt_real_tripode)) if rf_x > width/2 : corr_rf_x = float(rf_x) - (float(rf_x * alt_robot) / float(alt_real_tripode)) else: corr_rf_x = float(rf_x) + (float(rf_x * alt_robot) / float(alt_real_tripode)) return ro_x,corr_ro_y+20,rf_x,corr_rf_y+20
def change_by_hsv(self): avgs = self.get_avgs(self.hsv) for x in range(self.threshold.width): for y in range(self.threshold.height): if cv.Get2D(self.threshold, y, x)[0] == 255: val = cv.Get2D(self.hsv, y, x) difs = (val[0] - avgs[0], val[1] - avgs[1], val[2] - avgs[2]) cv.Set2D(self.hsv, y, x, (self.new_hsv[0] + difs[0], self.new_hsv[1] + difs[1], self.new_hsv[2] + difs[2])) cv.CvtColor(self.hsv, self.image_color, cv.CV_HSV2BGR)
def my_mouse_callback(event, x, y, flags, param): global evente, h, s, v, i, r, g, b, j global hsv_string global pos_string evente = event # Here event is left mouse button double-clicked if event == cv.CV_EVENT_LBUTTONDBLCLK: hsv = cv.CreateImage(cv.GetSize(frame), 8, 3) cv.CvtColor(frame, hsv, cv.CV_BGR2HSV) (h, s, v, i) = cv.Get2D(hsv, y, x) (r, g, b, j) = cv.Get2D(frame, y, x) hsv_string = str(cv.Get2D(hsv, y, x)) pos_string = '%s, %s' % (x, y)
def evento_mouse(event, x, y, flags, param): if event == cv.CV_EVENT_LBUTTONDOWN: pixel = cv.Get2D(imagen, y, x) print 'X =', x, ' Y =', y print 'R =', pixel[2], 'G =', pixel[1], 'B =', pixel[0] cv.InRangeS(imagen, (pixel[0] - tolerancia, pixel[1] - tolerancia, pixel[2] - tolerancia), (pixel[0] + tolerancia, pixel[1] + tolerancia, pixel[2] + tolerancia), temporal) cv.ShowImage('Color', temporal) for j in range(1, 480, 1): for i in range(1, 640, 1): c = cv.Get2D(temporal, j, i) if c[0] == 255: print j, i
def solve_linear(v1, v2, p1, p2): A = cv.CreateMat(2, 2, cv.CV_32FC1) B = cv.CreateMat(2, 1, cv.CV_32FC1) X = cv.CreateMat(2, 1, cv.CV_32FC1) cv.SetReal2D(A, 0, 0, v1[0]) cv.SetReal2D(A, 1, 0, v1[1]) cv.SetReal2D(A, 0, 1, -v2[0]) cv.SetReal2D(A, 1, 1, -v2[1]) cv.SetReal2D(B, 0, 0, p2[0] - p1[0]) cv.SetReal2D(B, 1, 0, p2[1] - p1[1]) cv.Solve(A, B, X) p = cv.Get2D(X, 0, 0) q = cv.Get2D(X, 1, 0) #print 'solving p1=',p1,'v1=',v1,'p2=',p2,'v2=',v2,'result=',(p[0],q[0]) return (p[0], q[0])
def avg_subwindow(image, subwindow_index): # this function should compute the average pixel intensity # in a given subwindow. # for now, we'll try just a simple average, # but Junaed's paper seems to talk about Gaussian # weighted averages. # if we just want to run through the video real quick if (SCAN): return 0 (firstX, firstY) = get_subwindow_location(subwindow_index) total = 0 count = 1 for x in range(firstX, firstX + SPATIAL_WINDOW_X - 1): for y in range(firstY, firstY + SPATIAL_WINDOW_Y - 1): # make sure our windows don't go outside the image if (x < WIDTH and y < HEIGHT): pixval = cv.Get2D(image, y, x) total += pixval[0] count += 1 return total / count
def __fill_image(self): last_was_move = True points = [] for i in range(self.__resized.rows): #for i in range(10): j = 0 for j in range(self.__resized.cols): value = cv.Get2D(self.__resized, i, j)[0] pixels = self.__fill_pixels(i, j) shifted_pixel = [] if pixels: if last_was_move: shifted_pixel.append((-self.__draww/2 + pixels[0][0] + j * self.__pixw, -(-self.__drawh/2 + pixels[0][1] + i * self.__pixh), MOVE_POINT)) last_was_move = False shifted = [(-self.__draww/2 + x[0] + j * self.__pixw, -(-self.__drawh/2 + x[1] + i * self.__pixh), DRAW_POINT) for x in pixels] shifted_pixel.extend(shifted) else: if points and not last_was_move: shifted_pixel = [(points[-1][0], points[-1][1], MOVE_POINT)] last_was_move = True points.extend(shifted_pixel) # Move pen to next line if not last_was_move: shifted_pixel = [(points[-1][0], points[-1][1], MOVE_POINT)] points.extend(shifted_pixel) last_was_move = True return points
def overlay_image(frame, image, x, y, w, h): """resize and overlay an image where a feature is detected This resizes the corresponding image to a matched feature, then loops through all of its pixels to superimpose the image on the frame """ # resize the image to fit the detected feature new_feature = cv.CreateImage((w, h), 8, 3) cv.Resize(image, new_feature, interpolation=cv.CV_INTER_AREA) # overlay the image on the frame for py in xrange(h): for px in xrange(w): pixel = cv.Get2D(new_feature, py, px) # don't map the whitespace surrounding the image if pixel != (255.0, 255.0, 255.0, 0.0): if image is tophat: # above feature new_y = y - py elif image is moustache: # bottom half of feature new_y = (h / 2) + y + py else: # over feature new_y = y + py new_x = x + px # make sure the image is in the frame if 0 < new_x < frame.width and 0 < new_y < frame.height: cv.Set2D(frame, new_y, new_x, pixel)
def setTreshold(event, x, y, flag, param): if(event == cv.CV_EVENT_LBUTTONDOWN): s = cv.Get2D(hsvImg, x , y) thresholdrange.append(s) temp = getMinMaxTreshold(thresholdrange) imageTreshold = thresholded_image(image, temp[0], temp[1]) cv.ShowImage('threshold', imageTreshold)
def getHsvRange(self): self.x_co = 0 self.y_co = 0 cv.NamedWindow('camera feed', cv.CV_WINDOW_AUTOSIZE) capture = cv.CaptureFromCAM(1) font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 0.5, 1, 0, 2, 8) while True: src = cv.QueryFrame(capture) # src = cv.LoadImage('2012_automata.jpg') cv.Smooth(src, src, cv.CV_BLUR, 3) hsv = cv.CreateImage(cv.GetSize(src), src.depth, 3) cv.CvtColor(src, hsv, cv.CV_BGR2HSV) cv.SetMouseCallback("camera feed", self.on_mouse, 0) s = cv.Get2D(hsv, self.y_co, self.x_co) # print "H:", s[0], " S:", s[1], " V:", s[2] cv.PutText(src, str(s[0]) + "," + str(s[1]) + "," + str(s[2]), (self.x_co, self.y_co), font, (55, 25, 255)) cv.ShowImage("camera feed", src) if cv.WaitKey(10) == 27: return (s[0], s[1], s[2]) break
def get_camPts_already_in_cam_frame(self): self.img = self.cvBridge.imgmsg_to_cv(self.img_msg) img_dotted = np.array( self.img) # = roscv.CloneImage(np.array(img)) doesn't # work between versions cv 2.0 and 2.1 height = self.img_msg.height width = self.img_msg.width N = len(self.cloud_msg.points) colors = np.zeros((3, N)) camPts = np.zeros((2, N)) camPts_idx = np.array([False for i in range(N)]) #list of boolean False's #billybob = tf.TransformerROS() #cloud_msg_cam_frame = billybob.transformPointCloud('base_footprint', self.cloud_msg) i = 0 for row in self.cloud_msg.points: pt3d = (row.x, row.y, row.z) uv = self.cam_model.project3dToPixel(pt3d) camPts[:, i] = uv x = uv[0] y = uv[1] if (x >= 0 and y >= 0 and x < width and y < height): roscv.Circle(img_dotted, uv, 0, (255, 100, 100)) row = int(y) col = int(x) r, g, b = (0, 1, 2) color = roscv.Get2D(self.img, row, col) colors[r, i] = color[r] colors[g, i] = color[g] colors[b, i] = color[b] camPts_idx[i] = True #else: print 'point ',uv,'out of bounds' i += 1 return camPts, camPts_idx, colors, img_dotted
def contrast(glcm): f2 = 0 for i in range(glcm.rows): for j in range(glcm.cols): val = cv.Get2D(glcm, i, j) f2 += ((i-j)**2)*val[0] print ";",f2
def _decode_rect(self, rect): ''' Reads binary code within rect using draw_img image Returns orientation of the code and decoded code @param rect: rectangle to use ''' gs = self.GRID_SIZE + 2 codel, _ = self._extract_code(rect, gs, .5, self.m_d.gray_img) code = self._get_code_matrix(codel, gs) if code is None: return self.FAILED, 0 bor = 0 for b in self.border: if code[b[0], b[1]] == 0: bor += 1 if bor < len(self.border) - 1: return self.FAILED, 0 first = self._find_first_corner(code, 1) if first == self.FAILED: return self.FAILED, 0 self._rotate_code(code, first) dec = 0 if self.m_d.flip_H: cv.Transpose(code, code) for (x, y) in reversed(self.code_points): dec *= 2 dec += cv.Get2D(code, y + 1, x + 1)[0] return first, dec
def _extract_code(self, rect, gs, offset, img): gsf = float(self.GRID_SIZE + 2) code = [] (a, b, c, d) = (rect[0], rect[1], rect[2], rect[3]) aa = ((d[0] - a[0]) / gsf, (d[1] - a[1]) / gsf) bb = ((c[0] - b[0]) / gsf, (c[1] - b[1]) / gsf) # lets first check if this is white_square in black or black in white #white_pixel = draw_img[int(a[0]- 0.5*aa[0]),int(a[1]-0.5*aa[1])] #black_pixel = draw_img[int(a[0]+ 0.5*aa[0]),int(a[1]+0.5*aa[1])] #if (white_pixel<black_pixel): # return self.FAILED,0 a = (a[0] + offset * aa[0], a[1] + offset * aa[1]) b = (b[0] + offset * bb[0], b[1] + offset * bb[1]) wx, wy = cv.GetSize(img) outsiders = [] for i in range(0, gs): p1 = (a[0] + i * aa[0], a[1] + i * aa[1]) p2 = (b[0] + i * bb[0], b[1] + i * bb[1]) cc = ((p2[0] - p1[0]) / gsf, (p2[1] - p1[1]) / gsf) p1 = (p1[0] + offset * cc[0], p1[1] + offset * cc[1]) for j in range(0, gs): x, y = (int(p1[0] + j * cc[0]), int(p1[1] + j * cc[1])) v = (0, 0, 0) if x < 0 or x >= wx or y < 0 or y >= wy: outsiders.append((i, j)) else: v = cv.Get2D(img, y, x) cv.Circle(self.m_d.draw_img, (x, y), 2, (0, 255, 0)) code.append(v) return code, outsiders
def mouse_callback(self, event, x, y, flags, param): if event == cv.CV_EVENT_LBUTTONDOWN: bgra = cv.Get2D(self.image, y, x) # hsv = cv.Get2D(self.hsv, y, x) # bgrhsv = bgra[:-1] + hsv[:-1] print "coords: (", x, ",", y, ")" print "bgra:", bgra blue = int(bgra[0]) green = int(bgra[1]) red = int(bgra[2]) # hue = int(bgrhsv[3]) # sat = int(bgrhsv[4]) # val = int(bgrhsv[5]) self.RGBvals.append((red, green, blue)) # self.HSVvals.append((hue,sat,val)) if len(self.RGBavgs) > 0: print self.RGBavgs print red, green, blue self.RGBavgs = ((self.RGBavgs[0] + red) / 2, (self.RGBavgs[1] + green) / 2, (self.RGBavgs[2] + blue) / 2) # self.HSVavgs = ((self.HSVavgs[0] + hue)/2, # (self.HSVavgs[1] + sat)/2, # (self.HSVavgs[2] + val)/2) else: self.RGBavgs = (red, green, blue) # self.HSVavgs = (hue, sat, val) print "RGBavgs:", self.RGBavgs print "RGBvals:", self.RGBvals # print "HSVavgs:", self.HSVavgs # print "HSVvals:", self.HSVvals rgbwindow = 50 # half the size of the window we want for thresholds # hsvwindow = 200 self.thresholds['low_red'] = self.RGBavgs[0] - rgbwindow self.thresholds['high_red'] = self.RGBavgs[0] + rgbwindow self.thresholds['low_green'] = self.RGBavgs[1] - rgbwindow self.thresholds['high_green'] = self.RGBavgs[1] + rgbwindow self.thresholds['low_blue'] = self.RGBavgs[2] - rgbwindow self.thresholds['high_blue'] = self.RGBavgs[2] + rgbwindow # self.thresholds['low_hue'] = self.HSVavgs[0] - hsvwindow # self.thresholds['high_hue'] = self.HSVavgs[0] + hsvwindow # self.thresholds['low_sat'] = self.HSVavgs[1] - hsvwindow # self.thresholds['high_sat'] = self.HSVavgs[1] + hsvwindow # self.thresholds['low_val'] = self.HSVavgs[2] - hsvwindow # self.thresholds['high_val'] = self.HSVavgs[2] + hsvwindow #Recreate the slider window cv.DestroyWindow('sliders') self.make_slider_window()
def corner_detection(image): img_or = cv.LoadImage(image) img = cv.LoadImage(image, cv.CV_LOAD_IMAGE_GRAYSCALE) w = img.width h = img.height print w, h cornerMap = cv.CreateMat(h, w, cv.CV_32FC1) print cornerMap #Harris Corner Detection cv.CornerHarris(img, cornerMap, 3) corners = [] #Recorriendo toda la imagen for x in range(0, h): for y in range(0, w): harris = cv.Get2D(cornerMap, x, y) #Validar la respuesta de deteccion de esquinas if harris[0] > 10e-06: #Dibujar un circulo en la imagen original cv.Circle(img_or, (y, x), 2, cv.RGB(155, 0, 25)) corners.append([y, x]) #Muestra la imagen y la guarda cv.ShowImage('Harris', img_or) cv.SaveImage('harris.jpg', img_or) cv.WaitKey() return corners, img
def __fill_pixels(self, r, c): fulld = self.__pixw / self.__stroke_width # Get the average of the pixels value = cv.Get2D(self.__resized, r, c)[0] actual = self.__map_range(value, 0, 255, 0, 1) ** (1 / self.__gamma) points = [] if actual > WHITE_THRESH: cv.Set2D(self.__output, r, c, 255) return [] elif actual > AMP_THRESH: up = self.__pixh * self.__map_range(actual, AMP_THRESH, WHITE_THRESH, (1 - OVERLAP), 0.5) down = self.__pixh * self.__map_range(actual, AMP_THRESH, WHITE_THRESH, OVERLAP, 0.5) cv.Set2D(self.__output, r, c, int(255 * actual)) points.append((self.__pixw / 2.0, down)) points.append((self.__pixw, up)) else: linecount = int(self.__map_range(actual, 0, AMP_THRESH, fulld, 1)) cv.Set2D(self.__output, r, c, int(AMP_THRESH*255 - ((linecount-1) / float(fulld-1)) ** (1/2.2) * AMP_THRESH*255)) gap = float(self.__pixw) / linecount up = self.__pixh * (1 - OVERLAP) down = self.__pixh * OVERLAP # Here is where the magic happens for i in range(linecount): points.append((gap * (i + 0.5), down)) points.append((gap * (i + 1), up)) return points
def flood_fill_edge(self, canny): width, height = cv.GetSize(canny) # set boarder pixels to white for x in range(width): cv.Set2D(canny, 0, x, self.white) cv.Set2D(canny, height - 1, x, self.white) for y in range(height): cv.Set2D(canny, y, 0, self.white) cv.Set2D(canny, y, width - 1, self.white) # prime to do list to_do = [(2, 2)] to_do.append([2, height - 3]) to_do.append([width - 3, height - 3]) to_do.append([width - 3, 2]) while len(to_do) > 0: x, y = to_do.pop() # get next pixel to test if cv.Get2D(canny, y, x)[0] == self.black[0]: # if black pixel found cv.Set2D(canny, y, x, self.white) # set pixel to white to_do.append([x, y - 1]) # add neighbours to to do list to_do.append([x, y + 1]) to_do.append([x - 1, y]) to_do.append([x + 1, y])
def make_gcode(self): self.output = "M106" # Start Fan nozzleFirings = [0 for x in range(0, self.img.cols)] nozzleFirings = [copy.copy(nozzleFirings) for x in range(0, 4)] scan = range(0, self.img.rows) scan.reverse() for y in scan: for x in range(0, self.img.cols): color = cv.Get2D(self.img, y, x) if color == self.red: nozzleFirings[0][x] += 1 << y % self.nozzles elif color == self.green: nozzleFirings[1][x] += 1 << y % self.nozzles elif color == self.blue: nozzleFirings[2][x] += 1 << y % self.nozzles elif color == self.black: nozzleFirings[3][x] += 1 << y % self.nozzles else: pass if y % 12 == 0 and y > 0: for headNumber, headVals in enumerate(nozzleFirings): for column, firingVal in enumerate(headVals): if firingVal: currentOffset = self.offsets[headNumber] self.output += "G1X"+str(self.increment*column-currentOffset[0])+"Y"+str(y/12*self.spread-currentOffset[1])+"F"+str(self.feedrate)+"\n" self.output += "M400\n" self.output += "M700 P"+str(headNumber)+" S"+str(firingVal)+"\n" print(str(nozzleFirings)) nozzleFirings = [0 for x in range(0, self.img.cols)] nozzleFirings = [copy.copy(nozzleFirings) for x in range(0, 4)] f = open(self.outFile, 'w') f.write(self.output) f.close() print(self.output)