我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cv2.LINE_AA。
def draw_rects(img, rects): """ ????????????? :param img: :param rects: :return: """ for x, y, w, h in rects: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 255, 00), 2) face = img face = cv2.resize(face,(224,224)) if Gender.predict(face)==1: text = "Male" else: text = "Female" cv2.putText(img, text, (x, h), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)
def test_image(addr): target = ['angry','disgust','fear','happy','sad','surprise','neutral'] font = cv2.FONT_HERSHEY_SIMPLEX im = cv2.imread(addr) gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray,scaleFactor=1.1) for (x, y, w, h) in faces: cv2.rectangle(im, (x, y), (x+w, y+h), (0, 255, 0), 2,5) face_crop = im[y:y+h,x:x+w] face_crop = cv2.resize(face_crop,(48,48)) face_crop = cv2.cvtColor(face_crop, cv2.COLOR_BGR2GRAY) face_crop = face_crop.astype('float32')/255 face_crop = np.asarray(face_crop) face_crop = face_crop.reshape(1, 1,face_crop.shape[0],face_crop.shape[1]) result = target[np.argmax(model.predict(face_crop))] cv2.putText(im,result,(x,y), font, 1, (200,0,0), 3, cv2.LINE_AA) cv2.imshow('result', im) cv2.imwrite('result.jpg',im) cv2.waitKey(0)
def update(self,frame,events): pts = [denormalize(pt['norm_pos'],frame.img.shape[:-1][::-1],flip_y=True) for pt in events.get('gaze_positions',[]) if pt['confidence']>=self.g_pool.min_data_confidence] bgra = (self.b*255,self.g*255,self.r*255,self.a*255) if pts: pts = np.array([pts],dtype=np.int32) cv2.polylines(frame.img, pts, isClosed=False, color=bgra, thickness=self.thickness, lineType=cv2.LINE_AA)
def transparent_circle(img,center,radius,color,thickness): center = tuple(map(int,center)) rgb = [255*c for c in color[:3]] # convert to 0-255 scale for OpenCV alpha = color[-1] radius = int(radius) if thickness > 0: pad = radius + 2 + thickness else: pad = radius + 3 roi = slice(center[1]-pad,center[1]+pad),slice(center[0]-pad,center[0]+pad) try: overlay = img[roi].copy() cv2.circle(img,center,radius,rgb, thickness=thickness, lineType=cv2.LINE_AA) opacity = alpha cv2.addWeighted(src1=img[roi], alpha=opacity, src2=overlay, beta=1. - opacity, gamma=0, dst=img[roi]) except: logger.debug("transparent_circle would have been partially outside of img. Did not draw it.")
def update(self,frame,events): pts = [denormalize(pt['norm_pos'],frame.img.shape[:-1][::-1],flip_y=True) for pt in events.get('gaze_positions',[]) if pt['confidence']>=self.g_pool.min_data_confidence] bgra = (self.b*255,self.g*255,self.r*255,self.a*255) for pt in pts: lines = np.array( [((pt[0]-self.inner,pt[1]),(pt[0]-self.outer,pt[1])),((pt[0]+self.inner,pt[1]),(pt[0]+self.outer,pt[1])) , ((pt[0],pt[1]-self.inner),(pt[0],pt[1]-self.outer)) , ((pt[0],pt[1]+self.inner),(pt[0],pt[1]+self.outer))],dtype=np.int32 ) cv2.polylines(frame.img, lines, isClosed=False, color=bgra, thickness=self.thickness, lineType=cv2.LINE_AA)
def drawPolylines(img, pts, isClosed, color, width): img = cv2.polylines(img, pts, isClosed, color, width, cv2.LINE_AA)
def draw_detection(image): candies = detector.detect(image) for candy in candies: cv2.polylines(image, np.int32([np.array(candy.box_coords)]), isClosed=True, color=(0, 0, 255), lineType=cv2.LINE_AA, thickness=3)
def put_text(img, i, layers, y): """ Put text on canvas :param img : Canvas :param i : i-th hidden layer, notice that layers[i].name is the name of i-th hidden layer :param layers : Layers :param y : (?, y) is the center of the neuron graph of i-th hidden layer """ ############################################################ # Write your code here! # ############################################################ cv2.putText(img, layers[i].name, (12, y - 36), cv2.LINE_AA, 0.6, (0, 0, 0), 1) ############################################################ # End # ############################################################
def vis_detections(im, class_name, dets, thresh=0.5): """Draw detected bounding boxes.""" inds = np.where(dets[:, -1] >= thresh)[0] if len(inds) == 0: return for i in inds: bbox = dets[i, :4] score = dets[i, -1] #Create Rectangle and Text using OpenCV #print ('ClassName:', class_name, 'bbox:', bbox, 'score:' ,score) #Draw the Rectangle cv2.rectangle(im, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 3) #Draw the Text cv2.putText(im, class_name + ' ' + str(score), (bbox[0], bbox[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2, cv2.LINE_AA) #Show Image #cv2.imshow("Detect Result", im)
def render(self, dst): t = self.t self.t += 1.0/30.0 l = 120 black = [245,245,245] white = [10,10,10] colors = [black,white] nsq = 0 x = 0 for xs in range(0,16): y = 0 for ys in range(0,9): fg = colors[nsq%2] bg = colors[(nsq+1) % 2] dst[y:y+l,x:x+l] = bg cv2.putText(dst, "%s" % nsq, (x+l/4, y+2*l/3), cv2.FONT_HERSHEY_PLAIN, 3, [0,0,255], thickness = 2, lineType=cv2.LINE_AA) y+=l nsq+=1 x+=l
def findSignificantContours(img, sobel_8u, sobel): image, contours, heirarchy = cv2.findContours(sobel_8u, \ cv2.RETR_EXTERNAL, \ cv2.CHAIN_APPROX_SIMPLE) mask = np.ones(image.shape[:2], dtype="uint8") * 255 level1 = [] for i, tupl in enumerate(heirarchy[0]): if tupl[3] == -1: tupl = np.insert(tupl, 0, [i]) level1.append(tupl) significant = [] tooSmall = sobel_8u.size * 10 / 100 for tupl in level1: contour = contours[tupl[0]]; area = cv2.contourArea(contour) if area > tooSmall: cv2.drawContours(mask, \ [contour], 0, (0, 255, 0), \ 2, cv2.LINE_AA, maxLevel=1) significant.append([contour, area]) significant.sort(key=lambda x: x[1]) significant = [x[0] for x in significant]; peri = cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, 0.02 * peri, True) mask = sobel.copy() mask[mask > 0] = 0 cv2.fillPoly(mask, significant, 255, 0) mask = np.logical_not(mask) img[mask] = 0; return img
def draw_rects(img, rects, color): """ ????????????? :param img: :param rects: :param color: :return: """ for x, y, w, h in rects: face = img[x:x+w,y:y+h] face = cv2.resize(face,(224,224)) if gender.predict(face)==1: text = "Male" else: text = "Female" cv2.rectangle(img, (x, y), (w, h), color, 2) cv2.putText(img, text, (x, h), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), lineType=cv2.LINE_AA)
def patText(s0): '''make text pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) s = int(round(s0/100.)) p1 = 0 pp1 = int(round(s0/10.)) for pos0 in np.linspace(0,s0,10): cv2.putText(arr, 'helloworld', (p1,int(round(pos0))), cv2.FONT_HERSHEY_COMPLEX_SMALL, fontScale=s, color=255, thickness=s, lineType=cv2.LINE_AA ) if p1: p1 = 0 else: p1 = pp1 return arr.astype(float)
def _mkConvKernel(ksize, orientations): # create line shaped kernels, like [ | / - \ ] for 4 orientations assert ksize[0] % 2 and ksize[1] % 2 k0, k1 = ksize mx, my = (k0 // 2) + 1, (k1 // 2) + 1 kernel = np.empty((orientations, k0, k1)) for i, a in enumerate(_angles(orientations)): # make line kernel x = int(round(4 * np.cos(a) * k0)) y = int(round(4 * np.sin(a) * k1)) k = np.zeros((2 * k0, 2 * k1), dtype=np.uint8) cv2.line(k, (-x + k0, -y + k1), (x + k0, y + k1), 255, thickness=1, lineType=cv2.LINE_AA) # resize and scale 0-1: ki = k[mx:mx + k0, my:my + k1].astype(float) / 255 kernel[i] = ki / ki.sum() return kernel
def drawAxis(camera_parameters, markers, frame): axis = np.float32([[1,0,0], [0,1,0], [0,0,1]]).reshape(-1,3) mtx, dist = camera_parameters.camera_matrix, camera_parameters.dist_coeff for marker in markers: rvec, tvec = marker.rvec, marker.tvec imgpts, jac = cv2.projectPoints(axis, rvec, tvec, mtx, dist) corners = marker.corners corner = tuple(corners[0].ravel()) cv2.line(frame, corner, tuple(imgpts[0].ravel()), (0,0,255), 2) cv2.line(frame, corner, tuple(imgpts[1].ravel()), (0,255,0), 2) cv2.line(frame, corner, tuple(imgpts[2].ravel()), (255,0,0), 2) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(frame, 'X', tuple(imgpts[0].ravel()), font, 0.5, (0,0,255), 2, cv2.LINE_AA) cv2.putText(frame, 'Y', tuple(imgpts[1].ravel()), font, 0.5, (0,255,0), 2, cv2.LINE_AA) cv2.putText(frame, 'Z', tuple(imgpts[2].ravel()), font, 0.5, (255,0,0), 2, cv2.LINE_AA)
def draw_correspondences(img, dstpoints, projpts): display = img.copy() dstpoints = norm2pix(img.shape, dstpoints, True) projpts = norm2pix(img.shape, projpts, True) for pts, color in [(projpts, (255, 0, 0)), (dstpoints, (0, 0, 255))]: for point in pts: cv2.circle(display, fltp(point), 3, color, -1, cv2.LINE_AA) for point_a, point_b in zip(projpts, dstpoints): cv2.line(display, fltp(point_a), fltp(point_b), (255, 255, 255), 1, cv2.LINE_AA) return display
def visualize_contours(name, small, cinfo_list): regions = np.zeros_like(small) for j, cinfo in enumerate(cinfo_list): cv2.drawContours(regions, [cinfo.contour], 0, CCOLORS[j % len(CCOLORS)], -1) mask = (regions.max(axis=2) != 0) display = small.copy() display[mask] = (display[mask]/2) + (regions[mask]/2) for j, cinfo in enumerate(cinfo_list): color = CCOLORS[j % len(CCOLORS)] color = tuple([c/4 for c in color]) cv2.circle(display, fltp(cinfo.center), 3, (255, 255, 255), 1, cv2.LINE_AA) cv2.line(display, fltp(cinfo.point0), fltp(cinfo.point1), (255, 255, 255), 1, cv2.LINE_AA) debug_show(name, 1, 'contours', display)
def visualize_span_points(name, small, span_points, corners): display = small.copy() for i, points in enumerate(span_points): points = norm2pix(small.shape, points, False) mean, small_evec = cv2.PCACompute(points.reshape((-1, 2)), None, maxComponents=1) dps = np.dot(points.reshape((-1, 2)), small_evec.reshape((2, 1))) dpm = np.dot(mean.flatten(), small_evec.flatten()) point0 = mean + small_evec * (dps.min()-dpm) point1 = mean + small_evec * (dps.max()-dpm) for point in points: cv2.circle(display, fltp(point), 3, CCOLORS[i % len(CCOLORS)], -1, cv2.LINE_AA) cv2.line(display, fltp(point0), fltp(point1), (255, 255, 255), 1, cv2.LINE_AA) cv2.polylines(display, [norm2pix(small.shape, corners, True)], True, (255, 255, 255)) debug_show(name, 3, 'span points', display)
def remove_blobs(image, min_area=0, max_area=sys.maxsize, threshold=128, method='8-connected', return_mask=False): """Binarize image using threshold, and remove (turn into black) blobs of connected pixels of white of size bigger or equal than min_area but smaller or equal than max_area from the original image, returning it afterward.""" method = method.lower() if method == '4-connected': method = cv2.LINE_4 elif method in ('16-connected', 'antialiased'): method = cv2.LINE_AA else: # 8-connected method = cv2.LINE_8 mono_image = binarize_image(image, method='boolean', threshold=threshold) _, all_contours, _ = cv2.findContours(mono_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) contours = np.array([contour for contour in all_contours if min_area <= cv2.contourArea(contour) <= max_area]) mask = np.ones(mono_image.shape, np.uint8) cv2.drawContours(mask, contours, -1, 0, -1, lineType=method) return image, 255 * mask
def camera_recog(): print("[INFO] camera sensor warming up...") vs = cv2.VideoCapture(0); #get input from webcam while True: _,frame = vs.read(); #u can certainly add a roi here but for the sake of a demo i'll just leave it as simple as this rects, landmarks = face_detect.detect_face(frame,80);#min face size is set to 80x80 aligns = [] positions = [] for (i, rect) in enumerate(rects): aligned_face, face_pos = aligner.align(160,frame,landmarks[i]) aligns.append(aligned_face) positions.append(face_pos) features_arr = extract_feature.get_features(aligns) recog_data = findPeople(features_arr,positions); for (i,rect) in enumerate(rects): cv2.rectangle(frame,(rect[0],rect[1]),(rect[0] + rect[2],rect[1]+rect[3]),(255,0,0)) #draw bounding box for the face cv2.putText(frame,recog_data[i][0]+" - "+str(recog_data[i][1])+"%",(rect[0],rect[1]),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),1,cv2.LINE_AA) cv2.imshow("Frame",frame) key = cv2.waitKey(1) & 0xFF if key == ord("q"): break
def detectFace(faces,hog,img): for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) result = cv2.face.MinDistancePredictCollector() rec.predict(hog[y:y+h,x:x+w],result, 0) id = result.getLabel() conf = result.getDist() if(conf<150): if(id==1): id="Ibrahim_"+str(conf) elif(id==2): id="Minh_"+str(conf) else: id="Hyeon_"+str(conf) else: id="Unknow" cv2.putText(img,str(id),(x,y+h),font,1,(255,255,255),2,cv2.LINE_AA)
def draw_text(self, image, text, size, color, position): ''' Zeichnet einen Text auf das Bild. Parameter --------- text : String Anzuzeigender Text size : Integer Groesse des Textes color : Tupel Farbe des Textes >> (255,0,0) position : Tupel Position des Textes >> (x,y) ''' if imutils.is_cv2(): cv2.putText(image, text, position, cv2.FONT_HERSHEY_COMPLEX, size, color, 2, cv2.CV_AA) elif imutils.is_cv3(): cv2.putText(image, text, position, cv2.FONT_HERSHEY_COMPLEX, size, color, 2, cv2.LINE_AA)
def markPoint(event, x, y, flags, param): global idx global data global input if event == cv2.EVENT_LBUTTONUP: data.append((x, y)) cv2.circle(input, (x, y), 3, (0,0,255), 2) cv2.putText(input, str(idx), (x, y+4), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 0), 2, cv2.LINE_AA) cv2.imshow("Mark points", input) idx = idx + 1
def cv2_demo(net, transform): def predict(frame): height, width = frame.shape[:2] x = torch.from_numpy(transform(frame)[0]).permute(2, 0, 1) x = Variable(x.unsqueeze(0)) y = net(x) # forward pass detections = y.data # scale each detection back up to the image scale = torch.Tensor([width, height, width, height]) for i in range(detections.size(1)): j = 0 while detections[0, i, j, 0] >= 0.6: pt = (detections[0, i, j, 1:] * scale).cpu().numpy() cv2.rectangle(frame, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])), COLORS[i % 3], 2) cv2.putText(frame, labelmap[i - 1], (int(pt[0]), int(pt[1])), FONT, 2, (255, 255, 255), 2, cv2.LINE_AA) j += 1 return frame # start video stream thread, allow buffer to fill print("[INFO] starting threaded video stream...") stream = WebcamVideoStream(src=0).start() # default camera time.sleep(1.0) # start fps timer # loop over frames from the video file stream while True: # grab next frame frame = stream.read() key = cv2.waitKey(1) & 0xFF # update FPS counter fps.update() frame = predict(frame) # keybindings for display if key == ord('p'): # pause while True: key2 = cv2.waitKey(1) or 0xff cv2.imshow('frame', frame) if key2 == ord('p'): # resume break cv2.imshow('frame', frame) if key == 27: # exit break
def drawLine(img, pt1, pt2, color, width): print(dir(cv2)) img = cv2.line(img, pt1, pt2, color, width, cv2.LINE_AA) # ????
def drawCircle(img, center, radius, color, width): img = cv2.circle(img, center, radius, color, width, cv2.LINE_AA) # ?????
def drawElipse(img, center, axes, angle, startAngle, endAngle, color, width): img = cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color, width, cv2.LINE_AA) # ??????
def drawRectangle(img, pt1, pt2, color, width): img = cv2.rectangle(img, pt1, pt2, color, width, cv2.LINE_AA) # ???????
def _drawString(image, target, string): x, y = target cv2.putText( image, string, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness=2, lineType=cv2.LINE_AA) cv2.putText( image, string, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)
def draw_str(dst, target, s, scale): x, y = target cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, scale, (0, 0, 0), thickness = 2, lineType=cv2.LINE_AA) cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, scale, (255, 255, 255), lineType=cv2.LINE_AA)
def draw_quads(self, img, quads, color = (0, 255, 0)): img_quads = cv2.projectPoints(quads.reshape(-1, 3), self.rvec, self.tvec, self.K, self.dist_coef) [0] img_quads.shape = quads.shape[:2] + (2,) for q in img_quads: cv2.fillConvexPoly(img, np.int32(q*4), color, cv2.LINE_AA, shift=2)
def circle_contour(image, contour): # Bounding ellipse image_with_ellipse = image.copy() #easy function ellipse = cv2.fitEllipse(contour) #add it cv2.ellipse(image_with_ellipse, ellipse, green, 2,cv2.LINE_AA) return image_with_ellipse
def mark(img, x, y): cv2.putText(img, 'O', (x - 15, y + 70), cv2.FONT_HERSHEY_SIMPLEX, 4, (255, 0, 0), 2, cv2.LINE_AA) buffer = BytesIO() imsave(buffer, img) return buffer
def draw_str(dst, pos, s): x,y = pos cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv2.LINE_AA) cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)
def __build_corner_template(size, directions): template = np.zeros((size, size), dtype=np.float32) a45 = pi / 4 a90 = pi / 2 a135 = pi / 2 + pi / 4 s = size // 2 for direction in directions: on_vertical_border = True sign = 1.0 if 0. <= direction < a45: beta = direction elif a45 <= direction < a90: beta = a90 - direction on_vertical_border = False elif a90 <= direction < a135: beta = direction - a90 on_vertical_border = False sign = -1.0 elif a135 <= direction < pi: beta = pi - direction sign = -1.0 else: raise ValueError("Illegal direction value: {:.3f}. Direction must be within [0, pi)".format(direction)) s_tan_beta = s * tan(beta) p0c0 = 0 p0c1 = int(0 + s + sign * s_tan_beta) p1c0 = 2 * s p1c1 = int(0 + s - sign * s_tan_beta) if on_vertical_border: p0 = (p0c0, p0c1) p1 = (p1c0, p1c1) else: p0 = (p0c1, p0c0) p1 = (p1c1, p1c0) cv2.line(template, p0, p1, 1, 3, cv2.LINE_AA) return template
def draw_text(coordinates, image_array, text, color=(255, 255, 255), x_offset=0, y_offset=0, font_scale=2, thickness=1): x, y = coordinates[:2] cv2.putText(image_array, text, (int(x + x_offset), int(y + y_offset)), cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, thickness, cv2.LINE_AA)
def plot_single_box_data(box_data, original_image_array, arg_to_class=None, class_arg=None, colors=None, font=FONT): image_shape = original_image_array.shape[0:2] box_data_length = len(box_data) # case after model predict if ((box_data_length > 4) and (class_arg is not None)): class_score = box_data[0] coordinates = box_data[1:] color = colors[class_arg] class_name = arg_to_class[class_arg] display_text = '{:0.2f}, {}'.format(class_score, class_name) x_min, y_min, x_max, y_max = denormalize_box(coordinates, image_shape) cv2.putText(original_image_array, display_text, (x_min, y_min - 10), font, .7, color, 1, cv2.LINE_AA) thickness = 2 # case for ground truth elif ((box_data_length > 4) and (class_arg is None)): class_scores = box_data[4:] class_arg = np.argmax(class_scores) class_score = class_scores[class_arg] coordinates = box_data[:4] color = colors[class_arg] class_name = arg_to_class[class_arg] display_text = '{:0.2f}, {}'.format(class_score, class_name) x_min, y_min, x_max, y_max = denormalize_box(coordinates, image_shape) cv2.putText(original_image_array, display_text, (x_min, y_min - 10), font, .4, color, 1, cv2.LINE_AA) thickness = 1 # case for only boxes coordinates elif box_data_length == 4: x_min, y_min, x_max, y_max = denormalize_box(box_data, image_shape) color = (255, 0, 0) thickness = 1 cv2.rectangle(original_image_array, (x_min, y_min), (x_max, y_max), color, thickness)
def patCircles(s0): '''make circle array''' arr = np.zeros((s0,s0), dtype=np.uint8) col = 255 for rad in np.linspace(s0,s0/7.,10): cv2.circle(arr, (0,0), int(round(rad)), color=col, thickness=-1, lineType=cv2.LINE_AA ) if col: col = 0 else: col = 255 return arr.astype(float)
def patCrossLines(s0): '''make line pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) col = 255 t = int(s0/100.) for pos in np.logspace(0.01,1,10): pos = int(round((pos-0.5)*s0/10.)) cv2.line(arr, (0,pos), (s0,pos), color=col, thickness=t, lineType=cv2.LINE_AA ) cv2.line(arr, (pos,0), (pos,s0), color=col, thickness=t, lineType=cv2.LINE_AA ) return arr.astype(float)
def patLinCrossLines(s0): '''make line pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) col = 255 t = int(s0/100.) for pos in np.linspace(0.,s0,10): pos = int(round(pos)) cv2.line(arr, (0,pos), (s0,pos), color=col, thickness=t, lineType=cv2.LINE_AA ) cv2.line(arr, (pos,0), (pos,s0), color=col, thickness=t, lineType=cv2.LINE_AA ) return arr.astype(float)
def patDiagCrossLines(s0): '''make line pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) col = 255 t = int(s0/50.) for pos in np.logspace(0.01,1,15): pos = int(round((pos-0.5)*s0/5.)) cv2.line(arr,(0,pos),(pos,0), color=col, thickness=t, lineType=cv2.LINE_AA ) cv2.line(arr,(s0-pos,0),(s0,pos), color=col, thickness=t, lineType=cv2.LINE_AA ) return arr.astype(float)
def patStarLines(s0): '''make line pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) col = 255 t = int(s0/100.) for pos in np.linspace(0,np.pi/2,15): p0 = int(round(np.sin(pos)*s0*2)) p1 = int(round(np.cos(pos)*s0*2)) cv2.line(arr,(0,0),(p0,p1), color=col, thickness=t, lineType=cv2.LINE_AA ) return arr.astype(float)
def cv2_demo(net, transform): def predict(frame): height, width = frame.shape[:2] x = Variable(transform(frame).unsqueeze(0)) y = net(x) # forward pass detections = y.data # scale each detection back up to the image scale = torch.Tensor([width, height, width, height]) for i in range(detections.size(1)): j = 0 while detections[0, i, j, 0] >= 0.6: pt = (detections[0, i, j, 1:] * scale).cpu().numpy() cv2.rectangle(frame, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])), COLORS[i % 3], 2) cv2.putText(frame, labelmap[i - 1], (int(pt[0]), int(pt[1])), FONT, 2, (255, 255, 255), 2, cv2.LINE_AA) j += 1 return frame # start video stream thread, allow buffer to fill print("[INFO] starting threaded video stream...") stream = WebcamVideoStream(src=0).start() # default camera time.sleep(1.0) # start fps timer # loop over frames from the video file stream while True: # grab next frame frame = stream.read() key = cv2.waitKey(1) & 0xFF # update FPS counter fps.update() frame = predict(frame) # keybindings for display if key == ord('p'): # pause while True: key2 = cv2.waitKey(1) or 0xff cv2.imshow('frame', frame) if key2 == ord('p'): # resume break cv2.imshow('frame', frame) if key == 27: # exit break
def drawOnImage(img, radius, AvgSentiment, key): img = cv2.circle(img,(x,y), radius, (0, 127.5+(AvgSentiment*127.5), 127.5+(AvgSentiment*-127.5)), -1) font = cv2.FONT_HERSHEY_PLAIN string = key #coordinates.append(str(x)+" "+str(y)+" "+key) cv2.putText(img,string,(x-8*len(string)-5,y), font, 2,(255,255,255),2,cv2.LINE_AA) string = str(value)+'+' cv2.putText(img,string,(x-8*len(string)-5,y+40), font, 2,(255,255,255),2,cv2.LINE_AA) return img
def drawMarkers(markers, frame): for marker in markers: drawCorners(marker.points, frame) center = marker.calculateCenter() cv2.circle(frame, center, 3, (0,0,255), 2) cv2.circle(frame, center, 5, (0,255,0), 2) cv2.circle(frame, center, 8, (255,0,0), 2) marker_id = marker.marker_id font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(frame, str(marker_id), center, font, 0.8, (0,0,255), 2, cv2.LINE_AA)