def DrawPoints(FaceDetected, image, mouth_color): faceInfoArray = FaceDetected[1] # Temporaneamente, solo per la prima faccia faceInfo = faceInfoArray[0] shapeInfo = faceInfo[0] extraInfo = faceInfo[1] # Ci interessano i punti della bocca mouthPoints = extraInfo[8] # Punto medio alphas = mouthPoints[::2] betas = mouthPoints[1::2] ma = sum(alphas) / len(alphas) mb = sum(betas) / len(betas) drawPointFromAngles(image, ma, mb, (0, 255, 0, 0)) for i in range(8): drawPointFromAngles(image, mouthPoints[2 * i], mouthPoints[2 * i + 1], mouth_color) x = toRelative(mouthPoints[0], mouthPoints[1]) y = toRelative(mouthPoints[2], mouthPoints[3]) cv.Line(image, x, y, (255, 255, 255, 0), 1) x = toRelative(mouthPoints[4], mouthPoints[5]) y = toRelative(mouthPoints[6], mouthPoints[7]) cv.Line(image, x, y, (255, 255, 255, 0), 1) pass
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 draw_line(self, x, y, direction, intersections): print 'draw_line', x, y, direction, intersections, len( self.grid_points_x), len(self.grid_points_y) if direction == 'H': print 'Draw H line', (0, y), (self.img_target.width, y) cv.Line(self.img_grid, (0, y), (self.img_target.width, y), cv.Scalar(0xff, 0x00, 0x00), 1) for gridx in self.grid_points_x: print '*****self.grid_points_x circle', (gridx, y), self.config.radius cv.Circle(self.img_grid, (gridx, y), self.config.radius, cv.Scalar(0x00, 0x00, 0x00), thickness=-1) cv.Circle(self.img_grid, (gridx, y), self.config.radius, cv.Scalar(0xff, 0x00, 0x00)) if intersections: self.grid_intersections.append((gridx, y)) else: cv.Line(self.img_grid, (x, 0), (x, self.img_target.height), cv.Scalar(0xff, 0x00, 0x00), 1) for gridy in self.grid_points_y: cv.Circle(self.img_grid, (x, gridy), self.config.radius, cv.Scalar(0x00, 0x00, 0x00), thickness=-1) cv.Circle(self.img_grid, (x, gridy), self.config.radius, cv.Scalar(0xff, 0x00, 0x00)) if intersections: self.grid_intersections.append((x, gridy)) show_image(self) print 'draw_line grid intersections:', len(self.grid_intersections)
def repeat(): global capture #declare as globals since we are assigning to them now global camera_index global done frame = cv.QueryFrame(capture) cv.Smooth(frame, frame, cv.CV_GAUSSIAN, 3, 3) imgHsv = cv.CreateImage(cv.GetSize(frame), 8, 3) cv.CvtColor(frame, imgHsv, cv.CV_BGR2HSV) #imgHsv2 = GetThresholdedImage(imgHsv) #print(numpy.asarray(cv.GetMat(imgHsv))) imgRGBA = cv.CreateImage(cv.GetSize(frame), 8, 4) cv.CvtColor(frame, imgRGBA, cv.CV_BGR2RGBA) cv.Smooth(imgRGBA, imgRGBA, cv.CV_GAUSSIAN, 3, 3) (filteredImg, offsetX, offsetY) = parallelSumRed(imgRGBA, 640, 480) #3D array d = numpy.sqrt(offsetX * offsetX + offsetY * offsetY) if d != 0: print("Distance = " + str(c1 / d + c2) + "cm") print("OffsetX = " + str(offsetX) + "; OffsetY = " + str(offsetY)) print("") imgRGB = cv.CreateImage(cv.GetSize(frame), 8, 3) #cv.CvtColor(Image.fromarray(filteredImg), imgRGB, cv.CV_RGBA2RGB) imgRGBA = cv.fromarray(numpy.reshape(filteredImg, (480, 640, 4))) if offsetX != 0 or offsetY != 0: cv.Rectangle(imgRGBA, (320 + offsetX - 6, 240 + offsetY - 6), (320 + offsetX + 6, 240 + offsetY + 6), (255, 0, 255, 255), 1, 8) cv.Line(imgRGBA, (0, 240 + offsetY), (639, 240 + offsetY), (255, 0, 255, 255), 1, 8) cv.Line(imgRGBA, (320 + offsetX, 0), (320 + offsetX, 479), (255, 0, 255, 255), 1, 8) cv.ShowImage(HSVWindow, imgRGBA) cv.ShowImage(original, frame) cv.SetMouseCallback(original, onMouseMove, [ cv.CV_EVENT_MOUSEMOVE, numpy.asarray(cv.GetMat(imgHsv)), numpy.asarray(cv.GetMat(frame)) ]) #cv.SetMouseCallback(HSVWindow, onMouseMove, [cv.CV_EVENT_MOUSEMOVE, numpy.asarray(cv.GetMat(imgHsv)), numpy.asarray(cv.GetMat(frame))]) #cv.ShowImage(filtered, imgHsv2) c = cv.WaitKey(10) if (str(c) == "27"): #if ESC is pressed print("Thank You!") done = True if (str(c) == "99"): #'c' for calibration calibration(int(input("How many data points: ")))
def lines2(): im = cv.LoadImage('roi_edges.jpg', cv.CV_LOAD_IMAGE_GRAYSCALE) pi = math.pi x = 0 dst = cv.CreateImage(cv.GetSize(im), 8, 1) cv.Canny(im, dst, 200, 200) cv.Threshold(dst, dst, 100, 255, cv.CV_THRESH_BINARY) color_dst_standard = cv.CreateImage(cv.GetSize(im), 8, 3) cv.CvtColor(im, color_dst_standard, cv.CV_GRAY2BGR) #Create output image in RGB to put red lines lines = cv.HoughLines2(dst, cv.CreateMemStorage(0), cv.CV_HOUGH_STANDARD, 1, pi / 100, 71, 0, 0) klsum = 0 klaver = 0 krsum = 0 kraver = 0 #global k #k=0 for (rho, theta) in lines[:100]: kl = [] kr = [] a = math.cos(theta) b = math.sin(theta) x0 = a * rho y0 = b * rho pt1 = (cv.Round(x0 + 1000 * (-b)), cv.Round(y0 + 1000 * (a))) pt2 = (cv.Round(x0 - 1000 * (-b)), cv.Round(y0 - 1000 * (a))) k = ((y0 - 1000 * (a)) - (y0 + 1000 * (a))) / ((x0 - 1000 * (-b)) - (x0 + 1000 * (-b))) if abs(k) < 0.4: pass elif k > 0: kr.append(k) len_kr = len(kr) for i in kr: krsum = krsum + i kraver = krsum / len_kr cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2, 4) elif k < 0: kr.append(k) kl.append(k) len_kl = len(kl) for i in kl: klsum = klsum + i klaver = klsum / len_kl cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2, 4) #print k # cv.Line(color_dst_standard, pt1, pt2, cv.CV_RGB(255, 0, 0), 2, 4) cv.SaveImage('lane.jpg', color_dst_standard) print '左车道平均斜率:', klaver, ' 右车道平均斜率:', kraver cv.ShowImage("Hough Standard", color_dst_standard) cv.WaitKey(0)
def linedraw(frame, dim, status, savePoint): frm = cv.fromarray(frame) pointx = (0 + 20, savePoint) pointy = (dim[0] - 20, savePoint) if status == "danger": cv.Line(frm, pointx, pointy, (255, 0, 0), 1) else: cv.Line(frm, pointx, pointy, (255, 255, 255), 1) return
def altera_quadro(): blink = cv.CloneImage(quadro) if maos: for id in maos: cv.Circle(blink, maos[id]['atual'], 10, cv.CV_RGB(0, 0, 150), -1, cv.CV_AA, 0) if 'anterior' in maos[id]: if efeito == 'Caneta': cv.Line(quadro, maos[id]['anterior'], maos[id]['atual'], cv.CV_RGB(0,0,0), 1, cv.CV_AA, 0) elif efeito == 'Apagador': cv.Line(quadro, maos[id]['anterior'], maos[id]['atual'], cv.CV_RGB(255,255,255), 30, cv.CV_AA, 0) cv.ShowImage('Quadro', blink)
def drawBoundingRect(self, frame, b_rect, smallSize = None): bounding_rect = [0,0,0,0] if smallSize != None: size = cv.GetSize(frame) scale = size[0] / float(smallSize[0]) bounding_rect[0] = int(b_rect[0] * scale) bounding_rect[1] = int(b_rect[1] * scale) bounding_rect[2] = int(b_rect[2] * scale) bounding_rect[3] = int(b_rect[3] * scale) l = 10 c = cv.CV_RGB(200,120,120) point1 = ( bounding_rect[0] - self._bRectOffset, bounding_rect[1] - self._bRectOffset ) point2 = ( bounding_rect[0] - self._bRectOffset, bounding_rect[1] + bounding_rect[3] + self._bRectOffset ) point3 = ( bounding_rect[0] + bounding_rect[2] + self._bRectOffset, bounding_rect[1] - self._bRectOffset ) point4 = ( bounding_rect[0] + bounding_rect[2] + self._bRectOffset, bounding_rect[1] + bounding_rect[3] + self._bRectOffset) cv.Line(frame, point1, (point1[0] + l, point1[1]) , c) cv.Line(frame, point1, (point1[0], point1[1] + l) , c) cv.Line(frame, point2, (point2[0] + l, point2[1]) , c) cv.Line(frame, point2, (point2[0], point2[1] - l) , c) cv.Line(frame, point3, (point3[0] - l, point3[1]) , c) cv.Line(frame, point3, (point3[0], point3[1] + l) , c) cv.Line(frame, point4, (point4[0] - l, point4[1]) , c) cv.Line(frame, point4, (point4[0], point4[1] - l) , c)
def draw(self): p1 = (0, 840) p2 = (int(self.w), 840) p3 = (0, 1040) p4 = (int(self.w), 1040) shift = int((self.w - 16 * len(self.text)) / 2) cv.PutText(self.src, self.text, (shift, 36), self.font, cv.Scalar(32, 0, 220, 0)) cv.PutText(self.src, str(self.iframe), (880, 52), self.font, cv.Scalar(32, 0, 220, 0)) cv.Line(self.src, p1, p2, cv.Scalar(0, 64, 255, 0), thickness=7) cv.Line(self.src, p1, p2, cv.Scalar(160, 0, 0, 0), thickness=2) cv.Line(self.src, p3, p4, cv.Scalar(0, 64, 255, 0), thickness=7) cv.Line(self.src, p3, p4, cv.Scalar(160, 0, 0, 0), thickness=2) self.showImg()
def draw_line(x, y, auto, direction, intersections): global Grid global Grid_Points_x global Grid_Points_y global Grid_Intersections # auto-center if auto: x_min = x while get_pixel(y, x_min) != 0.0: x_min -= 1 x_max = x while get_pixel(y, x_max) != 0.0: x_max += 1 x = x_min + ((x_max - x_min) / 2) y_min = y while get_pixel(y_min, x) != 0.0: y_min -= 1 y_max = y while get_pixel(y_max, x) != 0.0: y_max += 1 y = y_min + ((y_max - y_min) / 2) if direction == 'H': cv.Line(Grid, (0, y), (Target.width, y), cv.Scalar(0xff, 0x00, 0x00), 1) for gridx in Grid_Points_x: cv.Circle(Grid, (gridx, y), Radius, cv.Scalar(0x00, 0x00, 0x00), thickness=-1) cv.Circle(Grid, (gridx, y), Radius, cv.Scalar(0xff, 0x00, 0x00)) if intersections: Grid_Intersections.append((gridx, y)) else: cv.Line(Grid, (x, 0), (x, Target.height), cv.Scalar(0xff, 0x00, 0x00), 1) for gridy in Grid_Points_y: cv.Circle(Grid, (x, gridy), Radius, cv.Scalar(0x00, 0x00, 0x00), thickness=-1) cv.Circle(Grid, (x, gridy), Radius, cv.Scalar(0xff, 0x00, 0x00)) if intersections: Grid_Intersections.append((x, gridy)) show_image() print 'points:', len(Grid_Intersections) return x, y
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 get_G(x0, x1, y0, y1, width, height, side, data): G = nx.Graph() min_x, max_x, min_y, max_y = x0, x1, y0, y1 col = [] row = [] for tid in data.tid.unique(): themap = cv.CreateMat(height, width, cv.CV_16UC1) cv.SetZero(themap) for p in trajmap.pairwise(data[data.tid == tid].values): x0, y0, x1, y1 = p[0][1], p[0][2], p[1][1], p[1][2] oy = height - int((y0 - min_y) / side) ox = int((x0 - min_x) / side) dy = height - int((y1 - min_y) / side) dx = int((x1 - min_x) / side) cv.Line(themap, (ox, oy), (dx, dy), (32), 1, cv.CV_AA) node_set = set() for y, x in zip(*np.matrix(themap).nonzero()): node_set.add((x, y)) a = x + (height - y) * width for _x, _y in [(x - 1, y), (x, y - 1), (x - 1, y - 1), (x + 1, y), (x, y + 1), (x + 1, y + 1), (x - 1, y + 1), (x + 1, y - 1)]: if (_x, _y) in node_set: _a = _x + (height - _y) * width G.add_edge(a, _a) for tup in zip(*np.matrix(themap).nonzero()): row.append(tup[1] + (height - tup[0]) * width) col.append(tid) sag = scipy.sparse.csc_matrix(([1] * len(row), (row, col)), shape=(max(row) + 1, max(col) + 1)) return sag, G
def update_mhi(img, dst, diff_threshold): global last global mhi global storage global mask global orient global segmask timestamp = time.clock() / CLOCKS_PER_SEC # get current time in seconds size = cv.GetSize(img) # get current frame size idx1 = last if not mhi or cv.GetSize(mhi) != size: for i in range(N): buf[i] = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1) cv.Zero(buf[i]) mhi = cv.CreateImage(size,cv. IPL_DEPTH_32F, 1) cv.Zero(mhi) # clear MHI at the beginning orient = cv.CreateImage(size,cv. IPL_DEPTH_32F, 1) segmask = cv.CreateImage(size,cv. IPL_DEPTH_32F, 1) mask = cv.CreateImage(size,cv. IPL_DEPTH_8U, 1) cv.CvtColor(img, buf[last], cv.CV_BGR2GRAY) # convert frame to grayscale idx2 = (last + 1) % N # index of (last - (N-1))th frame last = idx2 silh = buf[idx2] cv.AbsDiff(buf[idx1], buf[idx2], silh) # get difference between frames cv.Threshold(silh, silh, diff_threshold, 1, cv.CV_THRESH_BINARY) # and threshold it cv.UpdateMotionHistory(silh, mhi, timestamp, MHI_DURATION) # update MHI cv.CvtScale(mhi, mask, 255./MHI_DURATION, (MHI_DURATION - timestamp)*255./MHI_DURATION) cv.Zero(dst) cv.Merge(mask, None, None, None, dst) cv.CalcMotionGradient(mhi, mask, orient, MAX_TIME_DELTA, MIN_TIME_DELTA, 3) if not storage: storage = cv.CreateMemStorage(0) seq = cv.SegmentMotion(mhi, segmask, storage, timestamp, MAX_TIME_DELTA) for (area, value, comp_rect) in seq: if comp_rect[2] + comp_rect[3] > 100: # reject very small components color = cv.CV_RGB(255, 0,0) silh_roi = cv.GetSubRect(silh, comp_rect) mhi_roi = cv.GetSubRect(mhi, comp_rect) orient_roi = cv.GetSubRect(orient, comp_rect) mask_roi = cv.GetSubRect(mask, comp_rect) angle = 360 - cv.CalcGlobalOrientation(orient_roi, mask_roi, mhi_roi, timestamp, MHI_DURATION) count = cv.Norm(silh_roi, None, cv.CV_L1, None) # calculate number of points within silhouette ROI if count < (comp_rect[2] * comp_rect[3] * 0.05): continue magnitude = 30. center = ((comp_rect[0] + comp_rect[2] / 2), (comp_rect[1] + comp_rect[3] / 2)) cv.Circle(dst, center, cv.Round(magnitude*1.2), color, 3, cv.CV_AA, 0) cv.Line(dst, center, (cv.Round(center[0] + magnitude * cos(angle * cv.CV_PI / 180)), cv.Round(center[1] - magnitude * sin(angle * cv.CV_PI / 180))), color, 3, cv.CV_AA, 0)
def update_drawing(): blink = cv.CloneImage(drawing) if hands: for id in hands: cv.Circle(blink, hands[id]['current_position'], 10, hands[id]['color']['cv'], -1, cv.CV_AA, 0) if hands[id]['drawing'] == True: cv.Line(drawing, hands[id]['previous_position'], hands[id]['current_position'], hands[id]['color']['cv'], 10, cv.CV_AA, 0) cv.ShowImage('Drawing', blink)
def draw_Lines(lines, img): for (rho, theta) in lines[:5]: a = cos(theta) b = sin(theta) x0 = a * rho y0 = b * rho pt1 = (cv.Round(x0 + 1000 * (-b)), cv.Round(y0 + 1000 * (a))) pt2 = (cv.Round(x0 - 1000 * (-b)), cv.Round(y0 - 1000 * (a))) cv.Line(img, pt1, pt2, cv.RGB(255, 0, 0), 3, 8)
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 repeat(): #每次从摄像头获取一张图片 frame = cv.QueryFrame(capture) image_size = cv.GetSize(frame)#获取图片的大小 #print image_size greyscale = cv.CreateImage(image_size, 8, 1)#建立一个相同大小的灰度图像 cv.CvtColor(frame, greyscale, cv.CV_BGR2GRAY)#将获取的彩色图像,转换成灰度图像 storage = cv.CreateMemStorage(0)#创建一个内存空间,人脸检测是要利用,具体作用不清楚 cv.EqualizeHist(greyscale, greyscale)#将灰度图像直方图均衡化,貌似可以使灰度图像信息量减少,加快检测速度 #画图像分割线 cv.Line(frame, (210,0),(210,480), (0,255,255),1) cv.Line(frame, (420,0),(420,480), (0,255,255),1) cv.Line(frame, (0,160),(640,160), (0,255,255),1) cv.Line(frame, (0,320),(640,320), (0,255,255),1) # detect objects cascade = cv.Load('/usr/share/OpenCV/haarcascades/haarcascade_frontalface_alt2.xml') #加载Intel公司的训练库 #检测图片中的人脸,并返回一个包含了人脸信息的对象faces faces = cv.HaarDetectObjects(greyscale, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100, 100)) #获得人脸所在位置的数据 for (x,y,w,h) , n in faces: # print x,y if x<210: print "right" elif x>310: print "left" cv.Rectangle(frame, (x,y), (x+w,y+h), (0,128,0),2)#在相应位置标识一个矩形 边框属性(0,0,255)红色 20宽度 cv.ShowImage("W1", greyscale)#显示互有边框的图片 cv.ShowImage("W1", frame)
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a line on the image''' pix1 = pixmapper(pt1) pix2 = pixmapper(pt2) clipped = cv.ClipLine((img.width, img.height), pix1, pix2) if clipped is None: return (pix1, pix2) = clipped cv.Line(img, pix1, pix2, colour, linewidth) cv.Circle(img, pix2, linewidth * 2, colour)
def draw_flow(self, flow, prevgray): """ Returns a nice representation of a hue histogram """ cv.CvtColor(prevgray, self.cflow, cv.CV_GRAY2BGR) for y in range(0, flow.height, self.mv_step): for x in range(0, flow.width, self.mv_step): fx, fy = flow[y, x] cv.Line(self.cflow, (x, y), (int(x + fx), int(y + fy)), self.mv_color) cv.Circle(self.cflow, (x, y), 2, self.mv_color, -1) cv.ShowImage("Optical Flow", self.cflow)
def on_mouse(self, event, x, y, flags, param): pt = (x, y) if event == cv.CV_EVENT_LBUTTONUP or not (flags & cv.CV_EVENT_FLAG_LBUTTON): self.prev_pt = None elif event == cv.CV_EVENT_LBUTTONDOWN: self.prev_pt = pt elif event == cv.CV_EVENT_MOUSEMOVE and (flags & cv.CV_EVENT_FLAG_LBUTTON) : if self.prev_pt: for dst in self.dests: cv.Line(dst, self.prev_pt, pt, cv.ScalarAll(255), 5, 8, 0) self.prev_pt = pt cv.ShowImage(self.windowname, img)
def draw_subdiv_edge(img, edge, color): org_pt = cv.Subdiv2DEdgeOrg(edge) dst_pt = cv.Subdiv2DEdgeDst(edge) if org_pt and dst_pt: org = org_pt.pt dst = dst_pt.pt iorg = (cv.Round(org[0]), cv.Round(org[1])) idst = (cv.Round(dst[0]), cv.Round(dst[1])) cv.Line(img, iorg, idst, color, 1, cv.CV_AA, 0)
def test_2542670(self): xys = [(94, 121), (94, 122), (93, 123), (92, 123), (91, 124), (91, 125), (91, 126), (92, 127), (92, 128), (92, 129), (92, 130), (92, 131), (91, 132), (90, 131), (90, 130), (90, 131), (91, 132), (92, 133), (92, 134), (93, 135), (94, 136), (94, 137), (94, 138), (95, 139), (96, 140), (96, 141), (96, 142), (96, 143), (97, 144), (97, 145), (98, 146), (99, 146), (100, 146), (101, 146), (102, 146), (103, 146), (104, 146), (105, 146), (106, 146), (107, 146), (108, 146), (109, 146), (110, 146), (111, 146), (112, 146), (113, 146), (114, 146), (115, 146), (116, 146), (117, 146), (118, 146), (119, 146), (120, 146), (121, 146), (122, 146), (123, 146), (124, 146), (125, 146), (126, 146), (126, 145), (126, 144), (126, 143), (126, 142), (126, 141), (126, 140), (127, 139), (127, 138), (127, 137), (127, 136), (127, 135), (127, 134), (127, 133), (128, 132), (129, 132), (130, 131), (131, 130), (131, 129), (131, 128), (132, 127), (133, 126), (134, 125), (134, 124), (135, 123), (136, 122), (136, 121), (135, 121), (134, 121), (133, 121), (132, 121), (131, 121), (130, 121), (129, 121), (128, 121), (127, 121), (126, 121), (125, 121), (124, 121), (123, 121), (122, 121), (121, 121), (120, 121), (119, 121), (118, 121), (117, 121), (116, 121), (115, 121), (114, 121), (113, 121), (112, 121), (111, 121), (110, 121), (109, 121), (108, 121), (107, 121), (106, 121), (105, 121), (104, 121), (103, 121), (102, 121), (101, 121), (100, 121), (99, 121), (98, 121), (97, 121), (96, 121), (95, 121)] #xys = xys[:12] + xys[16:] pts = cv.CreateMat(len(xys), 1, cv.CV_32SC2) for i,(x,y) in enumerate(xys): pts[i,0] = (x, y) storage = cv.CreateMemStorage() hull = cv.ConvexHull2(pts, storage) hullp = cv.ConvexHull2(pts, storage, return_points = 1) defects = cv.ConvexityDefects(pts, hull, storage) vis = cv.CreateImage((1000,1000), 8, 3) x0 = min([x for (x,y) in xys]) - 10 x1 = max([x for (x,y) in xys]) + 10 y0 = min([y for (y,y) in xys]) - 10 y1 = max([y for (y,y) in xys]) + 10 def xform(pt): x,y = pt return (1000 * (x - x0) / (x1 - x0), 1000 * (y - y0) / (y1 - y0)) for d in defects[:2]: cv.Zero(vis) # First draw the defect as a red triangle cv.FillConvexPoly(vis, [xform(p) for p in d[:3]], cv.RGB(255,0,0)) # Draw the convex hull as a thick green line for a,b in zip(hullp, hullp[1:]): cv.Line(vis, xform(a), xform(b), cv.RGB(0,128,0), 3) # Draw the original contour as a white line for a,b in zip(xys, xys[1:]): cv.Line(vis, xform(a), xform(b), (255,255,255)) self.snap(vis)
def on_mouse(self, event, x, y, flags, param): pt = (x, y) if event == cv.CV_EVENT_LBUTTONUP or not (flags & cv.CV_EVENT_FLAG_LBUTTON): self.prev_pt = None elif event == cv.CV_EVENT_LBUTTONDOWN: self.prev_pt = pt elif event == cv.CV_EVENT_MOUSEMOVE and (flags & cv.CV_EVENT_FLAG_LBUTTON): if self.prev_pt: for im in [self.image] + self.chans: cv.Line(im, self.prev_pt, pt, cv.ScalarAll(255), 5, 8, 0) self.prev_pt = pt cv.ShowImage("image", self.image) cv.ShowImage("LSB", self.chans[0])
def redraw_grid(): global Grid global Peephole global Radius global Grid_Points_x global Grid_Points_y global Grid_Intersections cv.Set(Grid, cv.Scalar(0, 0, 0)) cv.Set(Peephole, cv.Scalar(0, 0, 0)) Grid_Intersections = [] Grid_Points_x.sort() Grid_Points_y.sort() for x in Grid_Points_x: cv.Line(Grid, (x, 0), (x, Target.height), cv.Scalar(0xff, 0x00, 0x00), 1) for y in Grid_Points_y: Grid_Intersections.append((x, y)) Grid_Intersections.sort() for y in Grid_Points_y: cv.Line(Grid, (0, y), (Target.width, y), cv.Scalar(0xff, 0x00, 0x00), 1) for x, y in Grid_Intersections: cv.Circle(Grid, (x, y), Radius, cv.Scalar(0x00, 0x00, 0x00), thickness=-1) cv.Circle(Grid, (x, y), Radius, cv.Scalar(0xff, 0x00, 0x00), thickness=1) cv.Circle(Peephole, (x, y), Radius + 1, cv.Scalar(0xff, 0xff, 0xff), thickness=-1)
def draw_grid(grid): #bg = cv.Scalar(255, 255, 255) #cv.Rectangle(grid,(0,0),(grid.width,grid.width),bg, cv.CV_FILLED ) color = cv.Scalar(20, 70, 70) x = 0 while x < grid.width: #cv.Point cv.Line(grid, (x, 0), (x, grid.width), color, thickness=1, lineType=8, shift=0) x = x + 20 x = 0 while x < grid.height: #cv.Point cv.Line(grid, (0, x), (grid.width, x), color, thickness=1, lineType=8, shift=0) x = x + 20
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a line on the image''' pix1 = pixmapper(pt1) pix2 = pixmapper(pt2) clipped = cv.ClipLine((img.width, img.height), pix1, pix2) if clipped is None: if len(self._pix_points) == 0: self._pix_points.append(None) self._pix_points.append(None) return (pix1, pix2) = clipped cv.Line(img, pix1, pix2, colour, linewidth) cv.Circle(img, pix2, linewidth * 2, colour) if len(self._pix_points) == 0: self._pix_points.append(pix1) self._pix_points.append(pix2)
def drawrandline(): rand = Random() img = cv.CreateImage((700, 1000), 8, 3) cv.SetZero(img) cv.NamedWindow("RandomViewer", 1) for i in range(100): cv.Line(img, (rand.randrange(0, 700), rand.randrange(0, 1000)), (300, 200), (rand.randrange(0, 256), rand.randrange( 0, 256), rand.randrange(0, 256)), 1, 8, 0) cv.ShowImage("RandomViewer", img) cv.WaitKey(5) cv.PutText(img, "Hello OpenCV", (100, 200), cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 5, 10, 0, 1, 8), (255, 255, 255)) cv.ShowImage("RandomViewer", img) cv.WaitKey(0) cv.DestroyWindow("RandomViewer")
def hog_visualize(hog_image_v, integral_img, cell): hog_feat= [0] * 9 width_img,height_img = cv.GetSize(hog_image_v) halfcell = cell/2 num_cells_w,num_cells_h = width_img/cell,height_img/cell norient = integral_img.shape[2] mid = norient/2 for y in xrange(num_cells_h-1): for x in xrange(num_cells_w-1): px,py=x*cell,y*cell #features = integral_hog_window(integral_img, (px,py,max(px+8, width_img-1),max(py+8, height_img-1))) features = integral_hog_window(integral_img, (px, py, px+cell, py+cell)) hog_feat = hog_feat + list(features) px += halfcell py += halfcell #L1-norm, nice for visualization total = np.sum(features) maximum_value_feature = np.max(features) if total > 1e-3: normalized = features/maximum_value_feature N = norient final = [] for i in xrange(N): maximum_orient = normalized.argmax() valmax = normalized[maximum_orient] x1 = int(round(valmax*halfcell*np.sin(np.deg2rad(45*(maximum_orient-4))))) y1 = int(round(valmax*halfcell*np.cos(np.deg2rad(45*(maximum_orient-4))))) gradient_val = int(round(255*features[maximum_orient]/total)) #print "values of x1 =",x1,"and y1=",y1, "and gv=",gradient_val #don't draw if less than a threshold if gradient_val < 30: break final.insert(0, (x1,y1,gradient_val)) normalized[maximum_orient] = 0. #draw from smallest to highest gradient magnitude for i in xrange(len(final)): x1,y1,gradient_val = final[i] cv.Line(hog_image_v, (px-x1,py+y1), (px+x1,py-y1), cv.CV_RGB(gradient_val, gradient_val, gradient_val), 1, 8) else: #don't draw if there's no reponse pass return hog_feat
imgYellowTresh = getThresholdImage(frame) #Apply the threshold function moments = cv.Moments(cv.GetMat(imgYellowTresh), 1) moment10 = cv.GetSpatialMoment(moments, 1, 0) moment01 = cv.GetSpatialMoment(moments, 0, 1) area = cv.GetCentralMoment(moments, 0, 0) #Get the center lastx = posx lasty = posy if area == 0: posx = 0 posy = 0 else: posx = moment10 / area posy = moment01 / area if lastx > 0 and lasty > 0 and posx > 0 and posy > 0: #Mean we have received coordinates to print #Draw the line cv.Line(imgScribble, (int(posx), int(posy)), (int(lastx), int(lasty)), cv.Scalar(0, 255, 255), 3, 1) #Add the frame and the line image to see lines on the webcam frame cv.Add(frame, imgScribble, frame) cv.ShowImage("video", frame) cv.ShowImage("thresh", imgYellowTresh) c = cv.WaitKey(1) if c == 27 or c == 1048603: #Break if user enters 'Esc'. break elif c == 1048690: # 'r' for reset cv.Zero(imgScribble)
# note that the lower and upper bounds correspond to the the lower and upper bounds # in the getthresholdedimg(im): function earlier in the script. # e.g., yellow has a lowerbound of 95 and upper bound of 115 in both sections of code # UPDATED 9/22: 20 X AND Y PIXEL MINIMUM TO BE APPENDED TO CENTROID LISTS if (55 < cv.Get2D(imghsv,centroidy,centroidx)[0] < 155) and ypix > 20 and xpix > 20: blue.append((centroidx,centroidy)) # draw colors in windows; exception handling is used to avoid IndexError. # after drawing is over, centroid from previous part is removed from list by pop. # so in next frame, centroids in this frame become initial points of line to draw # draw blue box around blue blimp blob try: cv.Circle(imdraw, blue[1], 5, (255,0,0)) cv.Line(imdraw, blue[0], blue[1], (255,0,0), 3, 8, 0) print('xpix:'+str(xpix)) blue.pop(0) print("centroid x:" + str(centroidx)) print("centroid y:" + str(centroidy)) print("") except IndexError: print "no blimp detected" # adds cv.Add(test,imdraw,test) # display windows previously created cv.ShowImage("Real", color_image) if cv.WaitKey(33) == 1048603: