def getFeatures(self, grey): """ Returns a list of features generated by the OpenCV GoodFeaturesToTrack() function in the gray scale image 'gray'. """ #cv.ShowImage ('getFeatures() grey',grey) eig = cv.CreateImage(cv.GetSize(grey), 32, 1) temp = cv.CreateImage(cv.GetSize(grey), 32, 1) mask = cv.CreateImage(cv.GetSize(grey), 8, 1) # Create a mask image to hide the top 10% of the image (which contains text) (w, h) = cv.GetSize(grey) cv.Rectangle(mask, (0, 0), (w, h), cv.Scalar(255, 0, 0), -1) cv.Rectangle(mask, (0, 0), (w, int(0.1 * h)), cv.Scalar(0, 0, 0), -1) # cv.ShowImage ('mask',mask) # search for the good points feat = cv.GoodFeaturesToTrack(grey, eig, temp, self.MAX_COUNT, self.quality, self.min_distance, mask, 3, 0, 0.04) print "found %d features (MAX_COUNT=%d)" % (len(feat), self.MAX_COUNT) # refine the corner locations feat = cv.FindCornerSubPix( grey, feat, (self.win_size, self.win_size), (-1, -1), (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS, 20, 0.03)) return (feat)
def getthresholdedimg(im): #this fucntion takes the RGB image. Then converts it into HSV for easy color detection and thresholds it with yellow part imghsv=cv.CreateImage(cv.GetSize(im),8,3) cv.CvtColor(im,imghsv,cv.CV_BGR2HSV) imgthreshold=cv.CreateImage(cv.GetSize(im),8,1) cv.InRangeS(imghsv,cv.Scalar(20,100,100),cv.Scalar(30,255,255),imgthreshold) return imgthreshold
def display_pts(screen_in, q, P, IND): # Get New Point print('POINT ' + str(IND) + '\n') # If first point, start from center if (IND == 0): pt = np.array([N / 2, M / 2]) q.append(pt) cv2.circle(screen_in, (pt[0], pt[1]), 11, cv.Scalar(0, 255, 0), -1) return q, screen_in else: if (IND > P): #print('q before removal: '+str(q)+'\n') #q = q[1:] q.popleft() #print('q after removal: '+str(q)+'\n') #print('LENGTH - q =' +str(len(q))+'\n') pt = gen_random_pt(q[-1]) #pt = q[-1]+R q.append(pt) for i in range(0, len(q)): #print(str(q[i])+' ') cv2.circle(screen_in, (int(q[i][0]), int(q[i][1])), 11, cv.Scalar(0, 255, 0), -1) #print('\n') return q, screen_in
def getthresholdedimg(im): imghsv = cv.CreateImage(cv.GetSize(im), 8, 3) cv.CvtColor(im, imghsv, cv.CV_BGR2HSV) # Convert image from RGB to HSV imgthreshold = cv.CreateImage(cv.GetSize(im), 8, 1) cv.InRangeS(imghsv, cv.Scalar(23, 100, 100), cv.Scalar(25, 255, 255), imgthreshold) ## catch the orange yellow blob return imgthreshold
def getthresholdedimg(im): # this function take RGB image.Then convert it into HSV for easy colour detection # and threshold it with yellow and blue part as white and all other regions as black.Then return that image global imghsv imghsv = cv.CreateImage(cv.GetSize(im),8,3) # Convert image from RGB to HSV cv.CvtColor(im,imghsv,cv.CV_BGR2HSV) # creates images for blue imgblue = cv.CreateImage(cv.GetSize(im),8,1) # creates blank image to which color images are added imgthreshold = cv.CreateImage(cv.GetSize(im),8,1) # determine HSV color thresholds for yellow, blue, and green # cv.InRange(src, lowerbound, upperbound, dst) # for imgblue, lowerbound is 95, and upperbound is 115 cv.InRangeS(imghsv, cv.Scalar(55,100,100), cv.Scalar(155,255,255), imgblue) #55/155 original, 105 seems to be lower threshold needed to eliminate flag detection # add color thresholds to blank 'threshold' image cv.Add(imgthreshold, imgblue, imgthreshold) return imgthreshold
def blink_dot(img, pt, i): #, num_blinks): print('In Blink Dot') #for i in range(0,num_blinks): while 1: cv2.circle(img, pt, 11, cv.Scalar(255, 255, 255), -1) cv2.imshow("CALIB_SCREEN", img) key = cv.WaitKey(500) img = np.zeros(img.shape) cv2.imshow("CALIB_SCREEN", img) key = cv.WaitKey(500) if (key == 27): print('Dot Skipped!!') return if (key == 99): # If c is pressed, capture images capture_imgs(i) # Blink a Green Dot cv2.circle(img, pt, 11, cv.Scalar(0, 255, 0), -1) cv2.imshow("CALIB_SCREEN", img) key = cv.WaitKey(500) img = np.zeros(img.shape) cv2.imshow("CALIB_SCREEN", img) key = cv.WaitKey(500) return
def on_mouse_left(img_x, img_y, flags, param): self = param # Edit data if self.data_read: # find nearest intersection and toggle its value for x in self.grid_points_x: if img_x >= x - self.config.radius / 2 and img_x <= x + self.config.radius / 2: for y in self.grid_points_y: if img_y >= y - self.config.radius / 2 and img_y <= y + self.config.radius / 2: value = toggle_data(self, x, y) #print self.img_target[x, y] #print 'value', value if value == '0': cv.Circle(self.img_grid, (x, y), self.config.radius, cv.Scalar(0xff, 0x00, 0x00), thickness=2) else: cv.Circle(self.img_grid, (x, y), self.config.radius, cv.Scalar(0x00, 0xff, 0x00), thickness=2) show_image(self) # Edit grid else: #if not Target[img_y, img_x]: if flags != cv.CV_EVENT_FLAG_SHIFTKEY and not get_pixel( self, img_y, img_x): print 'autocenter: miss!' return if img_x in self.grid_points_x: return # only draw a single line if this is the first one if len(self.grid_points_x) == 0 or self.group_cols == 1: if flags != cv.CV_EVENT_FLAG_SHIFTKEY: img_x, img_y = auto_center(self, img_x, img_y) # don't try to auto-center if shift key pressed draw_line(self, img_x, img_y, 'V', False) self.grid_points_x.append(img_x) if self.group_rows == 1: draw_line(self, img_x, img_y, 'V', True) else: # set up auto draw if len(self.grid_points_x) == 1: # use a float to reduce rounding errors self.step_x = float(img_x - self.grid_points_x[0]) / ( self.group_cols - 1) # reset stored self.data as main loop will add all entries img_x = self.grid_points_x[0] self.grid_points_x = [] update_radius(self) # draw a full set of self.group_cols for x in range(self.group_cols): draw_x = int(img_x + x * self.step_x) self.grid_points_x.append(draw_x) draw_line(self, draw_x, img_y, 'V', True)
def getthresholdedimg(im): '''this function take RGB image.Then convert it into HSV for easy colour detection and threshold it with yellow part as white and all other regions as black.Then return that image''' imghsv = cv.CreateImage(cv.GetSize(im), 8, 3) cv.CvtColor(im, imghsv, cv.CV_BGR2HSV) # Convert image from RGB to HSV imgthreshold = cv.CreateImage(cv.GetSize(im), 8, 1) cv.InRangeS(imghsv, cv.Scalar(20, 100, 100), cv.Scalar(30, 255, 255), imgthreshold) # Select a range of yellow color return imgthreshold
def thresholdImage(img): # allocate temp image based on size of input img img_hsv = cv.CreateImage((img.width, img.height), 8, 3) # 3 channel img_thresh = cv.CreateImage((img.width, img.height), 8, 1) # 1 channel cv.CvtColor(img, img_hsv, cv.CV_BGR2HSV) cv.InRangeS(img_hsv, cv.Scalar(0, 100, 100), cv.Scalar(43, 255, 255), img_thresh) return (img_thresh)
def result_image(img, posX, posY, distance): hScale = 0.5 vScale = 0.5 lineWidth = 1 font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX | cv.CV_FONT_ITALIC, hScale, vScale, 0, lineWidth) cv.PutText(img, ("%0.2fcm" % distance), (10, 20), font, cv.Scalar(0, 255, 255)) cv.Circle(img, (posX, posY), 15, cv.Scalar(0, 255, 0), 2) cv.Circle(img, (posX, posY), 2, cv.Scalar(0, 255, 0), 2) return img
def draw_crossway(self, image, vertex_array, is_nearmiss): overlay = image.copy() color = cv.Scalar(255, 0, 0) if is_nearmiss: color = cv.Scalar(0, 0, 255) pts = numpy.array(vertex_array, numpy.int32) pts = pts.reshape((-1, 1, 2)) cv2.fillConvexPoly(overlay, pts, color) alpha = 0.5 cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0, image)
def getThresholdImage(im): newim = cv.CloneImage(im) cv.Smooth(newim, newim, cv.CV_BLUR, 12) #Remove noise hsv = cv.CreateImage(cv.GetSize(im), 8, 3) cv.CvtColor(newim, hsv, cv.CV_BGR2HSV) # Convert image to HSV imThreshed = cv.CreateImage(cv.GetSize(im), 8, 1) #Do the threshold on the hsv image, with the right range for the yellow color cv.InRangeS(hsv, cv.Scalar(20, 100, 100), cv.Scalar(30, 255, 255), imThreshed) del hsv return imThreshed
def read_data(self, data_ref=None, force=False): if not force and not self.data_read: return redraw_grid(self) # maximum possible value if all pixels are set maxval = (self.config.radius * self.config.radius) * 255 print 'read_data max aperture value:', maxval if data_ref: print 'read_data: loading reference data (%d entries)' % len(data_ref) print 'Grid intersections: %d' % len(self.grid_intersections) self.data = data_ref else: print 'read_data: computing' # Compute self.data = [] for x, y in self.grid_intersections: value = 0 # FIXME: misleading # This isn't a radius but rather a bounding box for xx in range(x - (self.config.radius / 2), x + (self.config.radius / 2)): for yy in range(y - (self.config.radius / 2), y + (self.config.radius / 2)): value += get_pixel(self, yy, xx) if value > maxval / self.config.bit_thresh_div: self.data.append('1') else: self.data.append('0') # Render for i, (x, y) in enumerate(self.grid_intersections): if self.data[i] == '1': cv.Circle(self.img_grid, (x, y), self.config.radius, cv.Scalar(0x00, 0xff, 0x00), thickness=2) # highlight if we're in edit mode if y == self.Edit_y: sx = self.Edit_x - (self.Edit_x % self.group_cols) if self.grid_points_x.index( x) >= sx and self.grid_points_x.index( x) < sx + self.group_cols: cv.Circle(self.img_grid, (x, y), self.config.radius, cv.Scalar(0xff, 0xff, 0xff), thickness=2) else: pass self.data_read = True
def drawLagoons(self, image) : global toggle global lagoon cler = [cv.Scalar(0,0,255,255),cv.Scalar(0,255,255,255),cv.Scalar(255,0,0,255),cv.Scalar(255,0,255,255)] i = 0 for bb in lagoon.values(): cv2.rectangle(image,(bb[0],bb[1]),(bb[0]+bb[2],bb[1]+bb[3]),cler[i%4],1) cv2.circle(image,(bb[0],bb[1]),5,cler[(i+1)%4],2) i = i + 1 if (image != None) : self.evocv2.showUser(image) else : plog(">>>>drawLagoons>>>\nimage was None in drawLagoons\n>>>>>>")
def getContour(cvImg): lowerBound = cv.Scalar(0, 0, 0) upperBound = cv.Scalar(3, 3, 3) size = cv.GetSize(cvImg) output = cv.CreateMat(size[0], size[1], cv.CV_8UC1) cv.InRangeS(cvImg, lowerBound, upperBound, output) storage = cv.CreateMemStorage(0) seq = cv.FindContours(output, storage, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_SIMPLE) mask = np.array(output) y, x = np.nonzero(mask) return (x, y)
def drawRects(self, image, outlines): # Create a different set of colors so the outlines are distinct cset = [ cv.Scalar(128, 0, 255, 255), cv.Scalar(255, 0, 0, 255), cv.Scalar(0, 255, 128, 255), cv.Scalar(0, 0, 255, 255) ] i = 0 for r in outlines: cv2.rectangle(image, (r[0], r[1]), (r[2], r[3]), cset[i % 4], 1) cv2.circle(image, (r[0], r[1]), 5, cset[(i + 1) % 4], 2) i = i + 1 self.showUser(image)
def drawBbs(self, image, outlines): # Create a set of colors so the outlines are distinct cset = [ cv.Scalar(0, 0, 255, 255), cv.Scalar(0, 255, 255, 255), cv.Scalar(255, 0, 0, 255), cv.Scalar(255, 0, 255, 255) ] i = 0 for bb in outlines: cv2.rectangle(image, (bb[0], bb[1]), (bb[0] + bb[2], bb[1] + bb[3]), cset[i % 4], 1) cv2.circle(image, (bb[0], bb[1]), 5, cset[(i + 1) % 4], 2) i = i + 1 self.showUser(image)
def show_camera_and_wait_for_key(capture, timeout=5, mapx=None, mapy=None): img = capture_image(capture, mapx, mapy) size = cv.GetSize(img) centerx = size[0] / 2 centery = size[1] / 2 crosslen = 4 cv.Line(img, (0, centery), (size[0], centery), cv.Scalar(255, 255, 0)) cv.Line(img, (centerx, 0), (centerx, size[1]), cv.Scalar(255, 255, 0)) cv.Line(img, (centerx - crosslen, centery), (centerx + crosslen, centery), cv.Scalar(255, 255, 0), 2) cv.Line(img, (centerx, centery - crosslen), (centerx, centery + crosslen), cv.Scalar(255, 255, 0), 2) cv.ShowImage('camera', img) k = cv.WaitKey(timeout) return img, k
def random_color(random): """ Return a random color """ icolor = random.randint(0, 0xFFFFFF) return cv.Scalar(icolor & 0xff, (icolor >> 8) & 0xff, (icolor >> 16) & 0xff)
def _random_color(self, name): """ Return a random color """ icolor = abs(hash(name)) % 0xFFFFFF return cv.Scalar(icolor & 0xff, (icolor >> 8) & 0xff, (icolor >> 16) & 0xff)
def redraw_grid(self): if not self.gui: return cv.Set(self.img_grid, cv.Scalar(0, 0, 0)) cv.Set(self.img_peephole, cv.Scalar(0, 0, 0)) self.grid_intersections = [] self.grid_points_x.sort() self.grid_points_y.sort() for x in self.grid_points_x: cv.Line(self.img_grid, (x, 0), (x, self.img_target.height), cv.Scalar(0xff, 0x00, 0x00), 1) for y in self.grid_points_y: self.grid_intersections.append((x, y)) self.grid_intersections.sort() for y in self.grid_points_y: cv.Line(self.img_grid, (0, y), (self.img_target.width, y), cv.Scalar(0xff, 0x00, 0x00), 1) for x, y in self.grid_intersections: cv.Circle(self.img_grid, (x, y), self.config.radius, cv.Scalar(0x00, 0x00, 0x00), thickness=-1) cv.Circle(self.img_grid, (x, y), self.config.radius, cv.Scalar(0xff, 0x00, 0x00), thickness=1) cv.Circle(self.img_peephole, (x, y), self.config.radius + 1, cv.Scalar(0xff, 0xff, 0xff), thickness=-1)
def drawGraph(ar, im, size): #Draw the histogram on the image minV, maxV, minloc, maxloc = cv.MinMaxLoc(ar) #Get the min and max value hpt = 0.9 * histsize for i in range(size): intensity = ar[ i] * hpt / maxV #Calculate the intensity to make enter in the image cv.Line(im, (i, size), (i, int(size - intensity)), cv.Scalar(255, 255, 255)) #Draw the line i += 1
def centerRadius(cvImg, ColorLower=None, ColorUpper=None): lowerBound = cv.Scalar(90, 0, 90) upperBound = cv.Scalar(171, 80, 171) size = cv.GetSize(cvImg) output = cv.CreateMat(size[0], size[1], cv.CV_8UC1) cv.InRangeS(cvImg, lowerBound, upperBound, output) yi, xi = np.nonzero(output) #points = np.array([xi,yi]).T #coords = [tuple(points[pt]) for pt in range(len(points))] coords = zip(xi, yi) PointArray2D32f = cv.CreateMat(1, len(coords), cv.CV_32FC2) for (i, (x, y)) in enumerate(coords): PointArray2D32f[0, i] = (x, y) (center, size, angle) = cv.FitEllipse2(PointArray2D32f) h, k = center radius = np.sqrt(np.power((xi[0] - h), 2) + np.power(yi[0] - k, 2)) return tuple(np.around([h, k])), round(radius)
def show_data(): global Hex global Display_Data global Display_Binary global Search_HEX global Grid_Points_x global Grid_Points_y global Font global Data_Read global Radius if not Data_Read: return cv.Set(Hex, cv.Scalar(0, 0, 0)) print dat = get_all_data() for row in range(Grid_Entries_y): out = '' outbin = '' for column in range(Grid_Entries_x / Bits): thisbyte = ord(dat[column * Grid_Entries_y + row]) hexbyte = '%02X ' % thisbyte out += hexbyte outbin += to_bin(thisbyte) + ' ' if Display_Binary: dispdata = to_bin(thisbyte) else: dispdata = hexbyte if Display_Data: if Search_HEX and Search_HEX.count(thisbyte): cv.PutText(Hex, dispdata, (Grid_Points_x[column * Bits], Grid_Points_y[row] + Radius / 2 + 1), Font, cv.Scalar(0x00, 0xff, 0xff)) else: cv.PutText(Hex, dispdata, (Grid_Points_x[column * Bits], Grid_Points_y[row] + Radius / 2 + 1), Font, cv.Scalar(0xff, 0xff, 0xff)) print outbin print print out print
def gen_mask(frec, tpoly): mask = cv.CreateMat(int(np.round(frec.height())), int(np.round(frec.width())), cv.CV_8UC1) cv.Zero(mask) pts = tuple((int(np.round(x - frec.left)), int(np.round(y - frec.top))) for (x, y) in tpoly.contour(0)) cv.FillPoly(mask, [pts], cv.Scalar(1), lineType=8, shift=0) return np.asarray(mask)
def findImage(img): #Set up storage for images frame_size = cv.GetSize(img) img2 = cv.CreateImage(frame_size,8,3) tmp = cv.CreateImage(frame_size,8,cv.CV_8U) h = cv.CreateImage(frame_size,8,1) #copy original image to do work on cv.Copy(img,img2) #altering the image a bit for smoother processing cv.Smooth(img2,img2,cv.CV_BLUR,3) cv.CvtColor(img2,img2,cv.CV_BGR2HSV) #make sure temp is empty cv.Zero(tmp) #detection based on HSV value #30,100,90 lower limit on pic 41,255,255 on pic #cv.InRangeS(img2,cv.Scalar(25,100,87),cv.Scalar(50,255,255),tmp) #Range for green plate dot in my Living room #cv.InRangeS(img2,cv.Scalar(55,80,60),cv.Scalar(65,95,90),tmp) #classroom #cv.InRangeS(img2,cv.Scalar(55,80,60),cv.Scalar(70,110,70),tmp) #Kutztowns Gym cv.InRangeS(img2,cv.Scalar(65,100,112),cv.Scalar(85,107,143),tmp) elmt_shape=cv.CV_SHAPE_ELLIPSE pos = 3 element = cv.CreateStructuringElementEx(pos*2+1, pos*2+1, pos, pos, elmt_shape) cv.Dilate(tmp,tmp,element,6) cv.Erode(tmp,tmp,element,2) cv.Split(tmp,h,None,None,None) storage = cv.CreateMemStorage() scan = sc.FindContours(h,storage) xyImage=drawCircles(scan,img) if xyImage != None: return (xyImage,tmp) else: return None
def colorFilter(img, color, calibrate): imgHSV = cv.CreateImage(cv.GetSize(img), 8, 3) cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV) if color == "yellow": minColor = cv.Scalar(20, 70, 70) maxColor = cv.Scalar(60, 255, 255) elif color == "blue": minColor = cv.Scalar(100, 100, 100) maxColor = cv.Scalar(120, 255, 255) elif color == "calibrate": minColor = cv.Scalar(calibrate[0], calibrate[1], calibrate[2]) maxColor = minColor imgFiltered = cv.CreateImage(cv.GetSize(img), 8, 1) cv.InRangeS(imgHSV, minColor, maxColor, imgFiltered) return imgFiltered
def test_40_tostringRepeat(self): cnt = 0 image = cv.CreateImage(self.size, cv.IPL_DEPTH_8U, 1) cv.Set(image, cv.Scalar(0, 0, 0, 0)) for i in range(self.repeat * 100): image.tostring() cnt = cv.CountNonZero(image) self.assertEqual(cnt, 0, msg="Repeating tostring(): Mean CountNonZero=%.3f" % (1. * cnt / self.repeat))
def drawPlate(self, plate=True): pos1 = (self.select.startX, self.select.startY) pos2 = (self.select.endX, self.select.endY) if (pos1[0] > pos2[0]) or (pos1[1] > pos2[1]): cor1 = cv.Scalar(0, 0, 255, 0) cor2 = cv.Scalar(255, 255, 255, 0) thick = 8 else: cor1 = cv.Scalar(36, 186, 255, 0) cor2 = cv.Scalar(8, 44, 72, 0) thick = 4 numpyImg = cv2.resize(numpy.asarray(self.src[:, :]), (0, 0), fx=self.fx, fy=self.fy) cimg = cv.fromarray(numpyImg) # draw plate if setted if plate: cv.Rectangle(cimg, pos1, pos2, cor1, thickness=thick) cv.Rectangle(cimg, pos1, pos2, cor2, thickness=2) cv.ShowImage("Camera", cimg)
def read_data(): global Grid_Intersections global Grid_Entries_x global Grid_Entries_y global Radius global Target global Bits global Data_Read global Data global Inverted redraw_grid() # maximum possible value if all pixels are set maxval = (Radius * Radius) * 255 print 'max:', maxval Data = [] for x, y in Grid_Intersections: value = 0 for xx in range(x - (Radius / 2), x + (Radius / 2)): for yy in range(y - (Radius / 2), y + (Radius / 2)): value += get_pixel(yy, xx) if value > maxval / ReadVal: cv.Circle(Grid, (x, y), Radius, cv.Scalar(0x00, 0xff, 0x00), thickness=2) # highlight if we're in edit mode if y == Edit_y: sx = Edit_x - (Edit_x % Bits) if Grid_Points_x.index(x) >= sx and Grid_Points_x.index( x) < sx + Bits: cv.Circle(Grid, (x, y), Radius, cv.Scalar(0xff, 0xff, 0xff), thickness=2) Data.append('1') else: Data.append('0') Data_Read = True