我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cv2.addWeighted()。
def render_lane(image, corners, ploty, fitx, ): _, src, dst = perspective_transform(image, corners) Minv = cv2.getPerspectiveTransform(dst, src) # Create an image to draw the lines on warp_zero = np.zeros_like(image[:,:,0]).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) # Recast the x and y points into usable format for cv2.fillPoly() pts = np.vstack((fitx,ploty)).astype(np.int32).T # Draw the lane onto the warped blank image #plt.plot(left_fitx, ploty, color='yellow') cv2.polylines(color_warp, [pts], False, (0, 255, 0), 10) #cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0)) # Warp the blank back to original image space using inverse perspective matrix (Minv) newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0])) # Combine the result with the original image result = cv2.addWeighted(image, 1, newwarp, 0.3, 0) return result
def findCircles(fname, image, circles_directory): f = os.path.join(circles_directory, os.path.basename(fname) + ".pkl") if os.path.exists(f): circles = pickle.load(open(f, "rb")) return circles image_cols, image_rows, _ = image.shape gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.bilateralFilter(gray, 9, 75, 75) gray = cv2.addWeighted(gray, 1.5, blurred, -0.5, 0) gray = cv2.bilateralFilter(gray, 9, 75, 75) # # detect circles in the image dp = 1 c1 = 100 c2 = 15 print "start hough", fname circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, dp, image_cols / 8, param1=c1, param2=c2) print "finish hough", fname pickle.dump(circles, open(f, "wb")) if circles is None or not len(circles): return None return circles
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 visualize(frame, coordinates_list, alpha = 0.80, color=[255, 255, 255]): """ Args: 1. frame: OpenCV's image which has to be visualized. 2. coordinates_list: List of coordinates which will be visualized in the given `frame` 3. alpha, color: Some parameters which help in visualizing properly. A convex hull will be shown for each element in the `coordinates_list` """ layer = frame.copy() output = frame.copy() for coordinates in coordinates_list: c_hull = cv2.convexHull(coordinates) cv2.drawContours(layer, [c_hull], -1, color, -1) cv2.addWeighted(layer, alpha, output, 1 - alpha, 0, output) cv2.imshow("Output", output)
def create_heatmaps(img, pred): """ Uses objectness probability to draw a heatmap on the image and returns it """ # find anchors with highest prediction best_pred = np.max(pred[..., 0], axis=-1) # convert probabilities to colormap scale best_pred = np.uint8(best_pred * 255) # apply color map # cv2 colormaps create BGR, not RGB cmap = cv2.cvtColor(cv2.applyColorMap(best_pred, cv2.COLORMAP_JET), cv2.COLOR_BGR2RGB) # resize the color map to fit image cmap = cv2.resize(cmap, img.shape[1::-1], interpolation=cv2.INTER_NEAREST) # overlay cmap with image return cv2.addWeighted(cmap, 1, img, 0.5, 0)
def transparent_image_overlay(pos,overlay_img,img,alpha): """ Overlay one image with another with alpha blending In player this will be used to overlay the eye (as overlay_img) over the world image (img) Arguments: pos: (x,y) position of the top left corner in numpy row,column format from top left corner (numpy coord system) overlay_img: image to overlay img: destination image alpha: 0.0-1.0 """ roi = slice(pos[1],pos[1]+overlay_img.shape[0]),slice(pos[0],pos[0]+overlay_img.shape[1]) try: cv2.addWeighted(overlay_img,alpha,img[roi],1.-alpha,0,img[roi]) except: logger.debug("transparent_image_overlay was outside of the world image and was not drawn") pass
def mark_point(img, x, y): """ Mark a point Args: - img(numpy): the source image - x, y(int): position """ overlay = img.copy() output = img.copy() alpha = 0.5 radius = max(5, min(img.shape[:2])//15) center = int(x), int(y) color = (0, 0, 255) cv2.circle(overlay, center, radius, color, -1) cv2.addWeighted(overlay, alpha, output, 1-alpha, 0, output) return output
def draw_countdown(self, frame): # Draw the count "3..". countdown_x_offset = 1 + self.countdown # Offset from left edge countdown_x = int(self.screenwidth - (self.screenwidth / 5) * countdown_x_offset) self.overlay = frame.copy() countdown_panel_y1 = int(self.screenheight * (4. / 5)) cv2.rectangle(self.overlay, (0, countdown_panel_y1), (self.screenwidth, self.screenheight), (224, 23, 101), -1) cv2.addWeighted(self.overlay, OPACITY, frame, 1 - OPACITY, 0, frame) countdown_y_offset = 20 countdown_y = int((self.screenheight * 7. / 8) + countdown_y_offset) countdown_coord = (countdown_x, countdown_y) draw_text(countdown_coord, frame, str(self.countdown)) return frame
def put_date(file, date): base_img_cv2 = cv2.imread(file) base_img = Image.open(file).convert('RGBA') txt = Image.new('RGB', base_img.size, (0, 0, 0)) draw = ImageDraw.Draw(txt) fnt = ImageFont.truetype('./Arial Black.ttf', size=(int)((base_img.size[0]+base_img.size[1])/100)) textw, texth = draw.textsize(date, font=fnt) draw.text(((base_img.size[0]*0.95 - textw) , (base_img.size[1]*0.95 - texth)), date, font=fnt, fill=font_color) txt_array = np.array(txt) output_img = cv2.addWeighted(base_img_cv2, 1.0, txt_array, 1.0, 0) return output_img
def draw_debug(img, pose, gt_pose, tracker, alpha, debug_info): if debug_info is not None: img_render, bb, _ = debug_info img_render = cv2.resize(img_render, (bb[2, 1] - bb[0, 1], bb[1, 0] - bb[0, 0])) crop = img[bb[0, 0]:bb[1, 0], bb[0, 1]:bb[2, 1], :] h, w, c = crop.shape blend = image_blend(img_render[:h, :w, ::-1], crop) img[bb[0, 0]:bb[1, 0], bb[0, 1]:bb[2, 1], :] = cv2.addWeighted(img[bb[0, 0]:bb[1, 0], bb[0, 1]:bb[2, 1], :], 1 - alpha, blend, alpha, 1) else: axis = compute_axis(pose, tracker.camera, tracker.object_width, scale=(1000, -1000, -1000)) axis_gt = compute_axis(gt_pose, tracker.camera, tracker.object_width, scale=(1000, -1000, -1000)) cv2.line(img, tuple(axis_gt[0, ::-1]), tuple(axis_gt[1, ::-1]), (0, 0, 155), 3) cv2.line(img, tuple(axis_gt[0, ::-1]), tuple(axis_gt[2, ::-1]), (0, 155, 0), 3) cv2.line(img, tuple(axis_gt[0, ::-1]), tuple(axis_gt[3, ::-1]), (155, 0, 0), 3) cv2.line(img, tuple(axis[0, ::-1]), tuple(axis[1, ::-1]), (0, 0, 255), 3) cv2.line(img, tuple(axis[0, ::-1]), tuple(axis[2, ::-1]), (0, 255, 0), 3) cv2.line(img, tuple(axis[0, ::-1]), tuple(axis[3, ::-1]), (255, 0, 0), 3)
def draw_labels(img, labels, label_colors, convert=True): """ Draw the labels on top of the input image :param img: the image being classified :param labels: the output of the neural network :param label_colors: the label color map defined in the source :param convert: should the output be converted to RGB """ labels_colored = np.zeros_like(img) for label in label_colors: label_mask = labels == label labels_colored[label_mask] = label_colors[label] img = cv2.addWeighted(img, 1, labels_colored, 0.8, 0) if not convert: return img return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #-------------------------------------------------------------------------------
def put_date(file, date): base_img_cv2 = cv2.imread(file) base_img = Image.open(file).convert('RGBA') txt = Image.new('RGB', base_img.size, (0, 0, 0)) draw = ImageDraw.Draw(txt) fnt = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMono.ttf', size=(int)((base_img.size[0]+base_img.size[1])/100)) textw, texth = draw.textsize(date, font=fnt) draw.text(((base_img.size[0]*0.95 - textw) , (base_img.size[1]*0.95 - texth)), date, font=fnt, fill=font_color) txt_array = np.array(txt) output_img = cv2.addWeighted(base_img_cv2, 1.0, txt_array, 1.0, 0) return output_img
def img_sobel_binary(im, blur_sz): # ?????????????? img_blur = cv2.GaussianBlur(im,blur_sz,0) if len(img_blur.shape) == 3: blur_gray = cv2.cvtColor(img_blur,cv2.COLOR_BGR2GRAY) else: blur_gray = img_blur # ??Sobel???? sobelx = cv2.Sobel(blur_gray,cv2.CV_16S,1,0,ksize=3) abs_sobelx = np.absolute(sobelx) sobel_8u = np.uint8(abs_sobelx) img_show_hook("Sobel??", sobel_8u) # OTSU?????? ret, thd = cv2.threshold(sobel_8u, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) thd_abs = cv2.convertScaleAbs(thd) bgimg = cv2.addWeighted(thd_abs, 1, 0, 0, 0) img_show_hook("OTSU????", bgimg) return bgimg
def findCircles(image): image_cols, image_rows, _ = image.shape gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) first, second = getRescaledDimensions(gray.shape[1], gray.shape[0], HD_MAX_X, HD_MAX_Y) gray = cv2.resize(gray, (first, second)) blurred = cv2.bilateralFilter(gray, 9, 75, 75) gray = cv2.addWeighted(gray, 1.5, blurred, -0.5, 0) gray = cv2.bilateralFilter(gray, 9, 75, 75) # # detect circles in the image dp = 1 c1 = 100 c2 = 15 circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, dp, second / 8, param1=c1, param2=c2) if not len(circles): return None return circles[0][0]
def detect_optic_disk(image_rgb, disk_center, out_name): scale = 100 w_sum = cv2.addWeighted(image_rgb, 4, cv2.GaussianBlur(image_rgb, (0, 0), scale / 30), -4, 128)# * circular_mask + 128 * (1 - circular_mask) # Image.fromarray(np.mean(w_sum, axis=2).astype(np.uint8)).save(out_name) edges = canny(np.mean(w_sum, axis=2).astype(np.uint8), sigma=1., low_threshold=50.)#, high_threshold=100.) result = hough_ellipse(edges, threshold=10, min_size=45, max_size=55) result.sort(order='accumulator') best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) Image.fromarray(image_rgb).save(out_name)
def kaggle_BG(img, scale): # Create a mask from which the approximate retinal center can be calculated guide_mask = create_mask(img) retina_center = tuple((np.mean(np.argwhere(guide_mask), axis=0)).astype(np.uint8))[::-1] # Generate a circle of the approximate size, centered based on the guide mask cf = 1.2 circular_mask = np.zeros(img.shape) cv2.circle(circular_mask, retina_center, int(scale * cf), (1, 1, 1), -1, 8, 0) # Compute weight sum of image, blurred image and mask it w_sum = cv2.addWeighted(img, 4, cv2.GaussianBlur(img, (0, 0), scale / 30), -4, 128) * circular_mask + 128 * (1 - circular_mask) return w_sum.astype(np.uint8) # https://github.com/btgraham/SparseConvNet/blob/kaggle_Diabetic_Retinopathy_competition/Data/ # kaggleDiabeticRetinopathy/preprocessImages.py
def houghTransform(image, edges): rho = 2 theta = np.pi/180 threshold = 15 min_line_length = 40 max_line_gap = 20 line_image = np.copy(image)*0 #creating a blank to draw lines on # Run Hough on edge detected image lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap) # Iterate over the output "lines" and draw lines on the blank for line in lines: for x1,y1,x2,y2 in line: cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10) # Create a "color" binary image to combine with line image color_edges = np.dstack((edges, edges, edges)) # Draw the lines on the edge image combo = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0) return combo
def yellowgrayscale(image): #enhance yellow then find grayscale #image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # define range of yellow color in HSV #lower = np.array([40,40,40]) #upper = np.array([150,255,255]) #RGB limits lower = np.array([80,80,40]) upper = np.array([255,255,80]) # Threshold the HSV image to get only yellow colors mask = cv2.inRange(image, lower, upper) #show_image('mask',mask) # Bitwise-AND mask and original image res = cv2.bitwise_and(image,image, mask= mask) res = cv2.addWeighted(res, 1.0, image, 1.0, 0) res = grayscale(res) return res
def weighted_img(img, initial_img, ?=0.8, ?=1., ?=0.): """ `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: initial_img * ? + img * ? + ? NOTE: initial_img and img must be the same shape! """ return cv2.addWeighted(initial_img, ?, img, ?, ?) # In[8]:
def update_edge_mask(self, previous_mask, previous_line, slope_sign, thrs1, thrs2, debug): lines = cv2.HoughLinesP(self.edge, 1, np.pi / 180, 70, minLineLength = 10, maxLineGap = 200) lines = filter_lines(lines, self.vanishing_height, self.edge.shape[0], slope_sign) self.lines.extend(lines) mask = np.zeros(self.edge.shape, np.uint8) for line in lines: x1,y1,x2,y2 = line cv2.line(mask, (x1,y1),(x2,y2), 255, MASK_WIDTH) mask = cv2.addWeighted(mask, MASK_WEIGHT, previous_mask, 1 - MASK_WEIGHT, 0) #self.current_mask *= int(255.0 / self.current_mask.max()) previous_mask = mask.copy() _, mask = cv2.threshold(mask, 40, 255, cv2.THRESH_BINARY) masked_edges = cv2.morphologyEx(cv2.bitwise_and(self.edge, self.edge, mask = mask), cv2.MORPH_CLOSE, np.array([[1] * EDGE_DILATION] *EDGE_DILATION)) lines2 = cv2.HoughLinesP(masked_edges, 1, np.pi / 180, 70, minLineLength = 10, maxLineGap = 200) lines2 = filter_lines(lines2, self.vanishing_height, self.edge.shape[0], slope_sign) self.lines2.extend(lines2) for line in lines2: x1,y1,x2,y2 = line cv2.line(mask, (x1,y1),(x2,y2), 255, MASK_WIDTH) previous_line[0] = add(previous_line[0], (x2,y2)) previous_line[1] = add(previous_line[1], (x_at_y(self.edge.shape[0]*0.6, x1, y1, x2, y2), self.edge.shape[0]*0.6)) previous_line[0] = scale(previous_line[0], 1.0 / (len(lines2) + 1)) previous_line[1] = scale(previous_line[1], 1.0 / (len(lines2) + 1)) return masked_edges, mask, previous_mask, previous_line
def highlightRois(image, roisCoords, roiWidthHeight): rois = [] for roiCoord in roisCoords: roiTopLeft = roiCoord['topLeft'] name = roiCoord['name'] # extract the regions of interest from the image roiBottomRight = tuple([sum(x) for x in zip(roiTopLeft, roiWidthHeight)]) roi = image[roiTopLeft[1]:roiBottomRight[1], roiTopLeft[0]:roiBottomRight[0]] rois.append({'topLeft': roiTopLeft, 'bottomRight': roiBottomRight, 'area': roi, 'name': name}) # construct a darkened transparent 'layer' to darken everything # in the image except for the regions of interest mask = np.zeros(image.shape, dtype = "uint8") image = cv2.addWeighted(image, 0.25, mask, 0.75, 0) # put the original rois back in the image so that they look 'brighter' for roi in rois: image[roi['topLeft'][1]:roi['bottomRight'][1], roi['topLeft'][0]:roi['bottomRight'][0]] = roi['area'] cv2.putText(image, roi['name'][0], roi['topLeft'], cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255,255), 2) return image
def gradient_img(colorsrc): ''' http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/sobel_derivatives/sobel_derivatives.html ''' SCALE = 1 DELTA = 0 DDEPTH = cv2.CV_16S ## to avoid overflow graysrc = cv2.cvtColor(colorsrc, cv2.cv.CV_BGR2GRAY) graysrc = cv2.GaussianBlur(graysrc, (3, 3), 0) ## gradient X ## gradx = cv2.Sobel(graysrc, DDEPTH, 1, 0, ksize=3, scale=SCALE, delta=DELTA) gradx = cv2.convertScaleAbs(gradx) ## gradient Y ## grady = cv2.Sobel(graysrc, DDEPTH, 0, 1, ksize=3, scale=SCALE, delta=DELTA) grady = cv2.convertScaleAbs(grady) grad = cv2.addWeighted(gradx, 0.5, grady, 0.5, 0) return grad
def animpingpong(self): obj=self.Object res=None for t in obj.OutList: print t.Label img=t.ViewObject.Proxy.img.copy() if res==None: res=img.copy() else: #rr=cv2.subtract(res,img) #rr=cv2.add(res,img) aw=0.0+float(obj.aWeight)/100 bw=0.0+float(obj.bWeight)/100 print aw print bw if obj.aInverse: # b umsetzen ret, mask = cv2.threshold(img, 50, 255, cv2.THRESH_BINARY) img=cv2.bitwise_not(mask) rr=cv2.addWeighted(res,aw,img,bw,0) res=rr #b,g,r = cv2.split(res) cv2.imshow(obj.Label,res) #cv2.imshow(obj.Label +" b",b) #cv2.imshow(obj.Label + " g",g) #cv2.imshow(obj.Label + " r",r) res=img if not obj.matplotlib: cv2.imshow(obj.Label,img) else: from matplotlib import pyplot as plt # plt.subplot(121), plt.imshow(img,cmap = 'gray') plt.title(obj.Label), plt.xticks([]), plt.yticks([]) plt.show() self.img=img
def weighted_img(img, initial_img, ?=0.8, ?=1., ?=0.): """ `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: initial_img * ? + img * ? + ? NOTE: initial_img and img must be the same shape! """ return cv2.addWeighted(initial_img, ?, img, ?, ?)
def _drawSpeed(image, speed, frameHeight=480, frameWidth=640): maxBars = 8 numBars = min(int(speed/6)+1, maxBars) # 6 m/s per speed bar for i in xrange(maxBars): overlay = image.copy() color = (10, 42*i, 42*(maxBars-1-i)) # BGR cv2.rectangle( overlay, (i*20, frameHeight-i*10), (frameWidth-i*20, frameHeight-(i+1)*10), color, thickness=-1) opacity = 0.08 cv2.addWeighted(overlay, opacity, image, 1-opacity, 0, image) if i <= numBars: # Shade bars to represent the speed opacity = 0.4 cv2.addWeighted(overlay, opacity, image, 1-opacity, 0, image)
def overlay_mask(mask, image): #make the mask rgb rgb_mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB) #calculates the weightes sum of two arrays. in our case image arrays #input, how much to weight each. #optional depth value set to 0 no need img = cv2.addWeighted(rgb_mask, 0.5, image, 0.5, 0) return img
def road_lines(image): """ Takes in a road image, re-sizes for the model, predicts the lane to be drawn from the model in G color, recreates an RGB image of a lane and merges with the original road image. """ # Get image ready for feeding into model small_img = imresize(image, (80, 160, 3)) small_img = np.array(small_img) small_img = small_img[None,:,:,:] # Make prediction with neural network (un-normalize value by multiplying by 255) prediction = model.predict(small_img)[0] * 255 # Add lane prediction to list for averaging lanes.recent_fit.append(prediction) # Only using last five for average if len(lanes.recent_fit) > 5: lanes.recent_fit = lanes.recent_fit[1:] # Calculate average detection lanes.avg_fit = np.mean(np.array([i for i in lanes.recent_fit]), axis = 0) # Generate fake R & B color dimensions, stack with G blanks = np.zeros_like(lanes.avg_fit).astype(np.uint8) lane_drawn = np.dstack((blanks, lanes.avg_fit, blanks)) # Re-size to match the original image lane_image = imresize(lane_drawn, (720, 1280, 3)) # Merge the lane drawing onto the original image result = cv2.addWeighted(image, 1, lane_image, 1, 0) return result
def sharpen_deblur(image): img = cv2.imread(image) output = cv2.GaussianBlur(img, (0, 0), 25) output = cv2.addWeighted(img, 1.75, output, -0.75, 0) os.remove(image) cv2.imwrite(image, output)
def predict_image(flag): t_start = cv2.getTickCount() config = tf.ConfigProto() # config.gpu_options.per_process_gpu_memory_fraction = 0.9 config.gpu_options.allow_growth = True set_session(tf.Session(config=config)) with open(os.path.join(flag.ckpt_dir, flag.ckpt_name, 'model.json'), 'r') as json_file: loaded_model_json = json_file.read() model = model_from_json(loaded_model_json) weight_list = sorted(glob(os.path.join(flag.ckpt_dir, flag.ckpt_name, "weight*"))) model.load_weights(weight_list[-1]) print "[*] model load : %s"%weight_list[-1] t_total = (cv2.getTickCount() - t_start) / cv2.getTickFrequency() * 1000 print "[*] model loading Time: %.3f ms"%t_total imgInput = cv2.imread(flag.test_image_path, 0) input_data = imgInput.reshape((1,256,256,1)) t_start = cv2.getTickCount() result = model.predict(input_data, 1) t_total = (cv2.getTickCount() - t_start) / cv2.getTickFrequency() * 1000 print "Predict Time: %.3f ms"%t_total imgMask = (result[0]*255).astype(np.uint8) imgShow = cv2.cvtColor(imgInput, cv2.COLOR_GRAY2BGR) _, imgMask = cv2.threshold(imgMask, int(255*flag.confidence_value), 255, cv2.THRESH_BINARY) imgMaskColor = cv2.applyColorMap(imgMask, cv2.COLORMAP_JET) # imgZero = np.zeros((256,256), np.uint8) # imgMaskColor = cv2.merge((imgZero, imgMask, imgMask)) imgShow = cv2.addWeighted(imgShow, 0.9, imgMaskColor, 0.3, 0.0) output_path = os.path.join(flag.output_dir, os.path.basename(flag.test_image_path)) cv2.imwrite(output_path, imgShow) print "SAVE:[%s]"%output_path
def train_visualization_seg(self, model, epoch): image_name_list = sorted(glob(os.path.join(self.flag.data_path,'train/IMAGE/*/*.png'))) print image_name_list image_name = image_name_list[-1] image_size = self.flag.image_size imgInput = cv2.imread(image_name, self.flag.color_mode) output_path = self.flag.output_dir input_data = imgInput.reshape((1,image_size,image_size,self.flag.color_mode*2+1)) t_start = cv2.getTickCount() result = model.predict(input_data, 1) t_total = (cv2.getTickCount() - t_start) / cv2.getTickFrequency() * 1000 print "[*] Predict Time: %.3f ms"%t_total imgMask = (result[0]*255).astype(np.uint8) imgShow = cv2.cvtColor(imgInput, cv2.COLOR_GRAY2BGR) imgMaskColor = cv2.applyColorMap(imgMask, cv2.COLORMAP_JET) imgShow = cv2.addWeighted(imgShow, 0.9, imgMaskColor, 0.4, 0.0) output_path = os.path.join(self.flag.output_dir, '%04d_'%epoch+os.path.basename(image_name)) cv2.imwrite(output_path, imgShow) # print "SAVE:[%s]"%output_path # cv2.imwrite(os.path.join(output_path, 'img%04d.png'%epoch), imgShow) # cv2.namedWindow("show", 0) # cv2.resizeWindow("show", 800, 800) # cv2.imshow("show", imgShow) # cv2.waitKey(1)
def weighted_img(img, initial_img, alpha=0.8, beta=1., lamda=0.): return cv2.addWeighted(initial_img, alpha, img, beta, lamda)
def processFrame(self): # If we are enhancing the image if self.enhance: # Frangi vesselness to highlight tubuar structures gray = cv2.cvtColor(self.sourceFrame, cv2.COLOR_BGR2GRAY) tub = tubes(gray, [5, 12]) tubular = cv2.cvtColor(tub, cv2.COLOR_GRAY2BGR) # Merge with original to ennhance tubular structures high = 0.3 rest = 1.0 - high colorized = cv2.addWeighted(self.sourceFrame, rest, tubular, high, 0.0) # colorized = cv2.add(self.sourceFrame, tubular) # Tile horizontally self.processedFrame = np.concatenate((self.sourceFrame, tubular, colorized), axis=1) else: self.processedFrame = self.sourceFrame; self.workingFrame = self.processedFrame.copy() # If we are tracking, track and show analysis if self.tracking is True: self.trackObjects() self.showBehavior()
def create_checkpoint_mask(img, mask, predicted_mask): p_mask = predicted_mask assert p_mask.shape[0] < p_mask.shape[1] if p_mask.shape == (CARVANA_H, CARVANA_W + 2): p_mask = p_mask[:, 1:-1] else: p_mask = cv2.resize(p_mask, (CARVANA_W, CARVANA_H), interpolation=cv2.INTER_NEAREST) p_mask = (p_mask > 0.5).astype(np.uint8) true_mask = mask_to_bgr(mask, 0, 255, 0) p_mask = mask_to_bgr(p_mask, 0, 0, 255) w = cv2.addWeighted(img, 1.0, true_mask, 0.3, 0) w = cv2.addWeighted(w, 1.0, p_mask, 0.5, 0) return w
def putTextAlpha(img, text, alpha, org, fontFace, fontScale, color, thickness): # , lineType=None ''' Extends cv2.putText with [alpha] argument ''' x, y = cv2.getTextSize(text, fontFace, fontScale, thickness)[0] ox, oy = org imgcut = img[oy - y - 3:oy, ox:ox + x] if img.ndim == 3: txtarr = np.zeros(shape=(y + 3, x, 3), dtype=np.uint8) else: txtarr = np.zeros(shape=(y + 3, x), dtype=np.uint8) cv2.putText(txtarr, text, (0, y), fontFace, fontScale, color, thickness=thickness #, lineType=lineType ) cv2.addWeighted(txtarr, alpha, imgcut, 1, 0, imgcut, -1) return img
def drawOpacityCircle(self, x, y, colorR, colorG, colorB, radius, thickness): overlay = self.frame.copy() cv2.circle(overlay, (x, y), radius, (colorB, colorG, colorR), thickness) alpha = 0.25 cv2.addWeighted(overlay, alpha, self.frame, 1 - alpha, 0, self.frame)
def generate( self ): # Create black background image and fill it up with random polygons img = np.zeros((self.height, self.width, 3), np.uint8) overlay = img.copy() output = img.copy() for i in range(self.size): info = self.genes[i].getInfo() if self.type == 1: cv2.circle(overlay,info[0], info[1], info[2], -1) cv2.addWeighted(overlay, info[3], output, 1 - info[3], 0, output) elif self.type == 2: cv2.ellipse(overlay,info[0],info[1],info[2],0,360,info[3],-1) cv2.addWeighted(overlay, info[4], output, 1 - info[4], 0, output) elif self.type == 3: cv2.fillConvexPoly(overlay,np.asarray(info[0]), info[1]) cv2.addWeighted(overlay, info[2], output, 1 - info[2], 0, output) elif self.type == 4: cv2.fillConvexPoly(overlay, np.asarray(info[0]), info[1]) cv2.addWeighted(overlay, info[2], output, 1 - info[2], 0, output ) return output
def outlining(img): #kernel size kernel_size=3 #------------------------------------------------- #bilateral filter, sharpen, thresh image biblur=cv2.bilateralFilter(img,20,175,175) sharp=cv2.addWeighted(img,1.55,biblur,-0.5,0) ret1,thresh1 = cv2.threshold(sharp,127,255,cv2.THRESH_OTSU) #negative and closed image inv=cv2.bitwise_not(thresh1) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size)) closed = cv2.morphologyEx(inv, cv2.MORPH_CLOSE, kernel) return closed
def getRGBS(img, PLOT = False): image = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) # grab the image channels, initialize the tuple of colors, # the figure and the flattened feature vector features = [] featuresSobel = [] Grayscale = cv2.cvtColor(img, cv2.cv.CV_BGR2GRAY) histG = cv2.calcHist([Grayscale], [0], None, [16], [0, 256]) histG = histG / histG.sum() features.extend(histG[:,0].tolist()) grad_x = np.abs(cv2.Sobel(Grayscale, cv2.CV_16S, 1, 0, ksize = 3, scale = 1, delta = 0, borderType = cv2.BORDER_DEFAULT)) grad_y = np.abs(cv2.Sobel(Grayscale, cv2.CV_16S, 0, 1, ksize = 3, scale = 1, delta = 0, borderType = cv2.BORDER_DEFAULT)) abs_grad_x = cv2.convertScaleAbs(grad_x) abs_grad_y = cv2.convertScaleAbs(grad_y) dst = cv2.addWeighted(abs_grad_x,0.5,abs_grad_y,0.5,0) histSobel = cv2.calcHist([dst], [0], None, [16], [0, 256]) histSobel = histSobel / histSobel.sum() features.extend(histSobel[:,0].tolist()) Fnames = [] Fnames.extend(["Color-Gray"+str(i) for i in range(8)]) Fnames.extend(["Color-GraySobel"+str(i) for i in range(8)]) return features, Fnames
def get_gradient(im): # Calculate the x and y gradients using Sobel operator grad_x = cv2.Sobel(im,cv2.CV_32F,1,0,ksize=3) grad_y = cv2.Sobel(im,cv2.CV_32F,0,1,ksize=3) # Combine the two gradients grad = cv2.addWeighted(np.absolute(grad_x), 0.5, np.absolute(grad_y), 0.5, 0) # print grad.dtype # print grad.shape return grad # Based on: http://www.learnopencv.com/image-alignment-ecc-in-opencv-c-python/
def ShowSolution(images, puzzle, solution, frame, box): cell_size = np.array([box.w / 4, box.h / 4]) for piece_type, piece, i, j in solution: top_left_loc = np.array([box.x, box.y]) + (np.array([j, i]) - np.array([1, 1])) * cell_size color = pieces.Colors[piece_type] piece_img = np.zeros_like(frame) for square in itertools.product(range(2), range(2)): if piece[square] == board.SquareType.AIR: continue loc = top_left_loc + np.array(square[::-1]) * cell_size piece_img = cv2.rectangle(piece_img, tuple(loc), tuple(loc + cell_size), color, -2) if piece[square] in images: image = cv2.resize(images[piece[square]], tuple(cell_size)) blend = np.zeros_like(piece_img) blend[loc[1]:loc[1] + cell_size[1], loc[0]:loc[0] + cell_size[ 0]] = image piece_img = cv2.addWeighted(piece_img, 1.0, blend, 1.0, 0) piece_gray = cv2.cvtColor(piece_img, cv2.COLOR_RGB2GRAY) _, piece_gray = cv2.threshold(piece_gray, 10, 255, cv2.THRESH_BINARY) _, contours, _ = cv2.findContours(piece_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) piece_img = cv2.drawContours(piece_img, contours, -1, (255, 255, 255), 3) frame = cv2.addWeighted(frame, 1.0, piece_img, 0.7, 0) cv2.imshow("Planes", frame)
def paintGL(self, sun_x, sun_y, sun_z, moon_x, moon_y, moon_z): # Draw the sun self.fbo.bind() self.draw_sun(sun_x, sun_y, sun_z) glFlush() self.fbo.release() image = self.fbo.toImage() # Produce blurred image of sun npimage = qimage_to_numpy(image) h, w, b = npimage.shape blur = cv2.GaussianBlur(npimage, (75, 75), 0, 0) cv2.convertScaleAbs(blur, blur, 2, 1) # Combine the blurred with the sun combo = cv2.addWeighted(blur, 0.5, npimage, 0.5, -1) h, w, b = combo.shape qimage = QtGui.QImage(combo.data,w,h,QtGui.QImage.Format_ARGB32).rgbSwapped() self.fbo.bind() device = QtGui.QOpenGLPaintDevice(RES_X, RES_Y) painter = QtGui.QPainter() painter.begin(device) rect = QtCore.QRect(0, 0, RES_X, RES_Y) # Draw the blurred sun/sun combo image on the screen painter.drawImage(rect, qimage, rect) painter.end() self.fbo.release() # Draw the moon self.fbo.bind() self.draw_moon(moon_x, moon_y, moon_z) glFlush() self.fbo.release()
def global_gradient(self): gradient_values_x = cv2.Sobel(self.img, cv2.CV_64F, 1, 0, ksize=5) gradient_values_y = cv2.Sobel(self.img, cv2.CV_64F, 0, 1, ksize=5) gradient_magnitude = cv2.addWeighted(gradient_values_x, 0.5, gradient_values_y, 0.5, 0) gradient_angle = cv2.phase(gradient_values_x, gradient_values_y, angleInDegrees=True) return gradient_magnitude, gradient_angle
def watershed(self): m = self.markers.copy() cv2.watershed(self.img, m) self.returnVar = m.copy() overlay = self.colors[np.maximum(m, 0)] vis = cv2.addWeighted(self.img, 0.5, overlay, 0.5, 0.0, dtype=cv2.CV_8UC3) cv2.namedWindow('watershed', cv2.WINDOW_NORMAL) cv2.moveWindow('watershed',780,200) cv2.imshow('watershed', vis)
def _get_gradient_magnitude(im): "Get magnitude of gradient for given image" ddepth = cv2.CV_32F dx = cv2.Sobel(im, ddepth, 1, 0) dy = cv2.Sobel(im, ddepth, 0, 1) dxabs = cv2.convertScaleAbs(dx) dyabs = cv2.convertScaleAbs(dy) mag = cv2.addWeighted(dxabs, 0.5, dyabs, 0.5, 0) return np.average(mag)
def highlight_regions(image, region_rects): # Darken image with mask composite_image = cv2.addWeighted(image, 0.50, numpy.zeros(image.shape, dtype="uint8"), 0.50, 0) # Highlight region_of_interest for rect in region_rects: (x1, x2, y1, y2) = (rect["x1"], rect["x2"], rect["y1"], rect["y2"]) composite_image[y1:y2, x1:x2] = image[y1:y2, x1:x2] return composite_image
def process_an_image(img): roi_vtx = np.array([[(0, img.shape[0]), (460, 325), (520, 325), (img.shape[1], img.shape[0])]]) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) blur_gray = cv2.GaussianBlur(gray, (blur_ksize, blur_ksize), 0, 0) edges = cv2.Canny(blur_gray, canny_lthreshold, canny_hthreshold) roi_edges = roi_mask(edges, roi_vtx) line_img = hough_lines(roi_edges, rho, theta, threshold, min_line_length, max_line_gap) res_img = cv2.addWeighted(img, 0.8, line_img, 1, 0) # plt.figure() # plt.imshow(gray, cmap='gray') # plt.savefig('../resources/gray.png', bbox_inches='tight') # plt.figure() # plt.imshow(blur_gray, cmap='gray') # plt.savefig('../resources/blur_gray.png', bbox_inches='tight') # plt.figure() # plt.imshow(edges, cmap='gray') # plt.savefig('../resources/edges.png', bbox_inches='tight') # plt.figure() # plt.imshow(roi_edges, cmap='gray') # plt.savefig('../resources/roi_edges.png', bbox_inches='tight') # plt.figure() # plt.imshow(line_img, cmap='gray') # plt.savefig('../resources/line_img.png', bbox_inches='tight') # plt.figure() # plt.imshow(res_img) # plt.savefig('../resources/res_img.png', bbox_inches='tight') # plt.show() return res_img # img = mplimg.imread("../resources/lane.jpg") # process_an_image(img)
def houghTransformAndRegionSelect(image, edges): rho = 1 theta = np.pi/180 threshold = 1 min_line_length = 5 max_line_gap = 3 # Next we'll create a masked edges image using cv2.fillPoly() mask = np.zeros_like(edges) ignore_mask_color = 255 # This time we are defining a four sided polygon to mask imshape = image.shape vertices = np.array([[(0,imshape[0]),(450, 290), (490, 290), (imshape[1],imshape[0])]], dtype=np.int32) cv2.fillPoly(mask, vertices, ignore_mask_color) masked_edges = cv2.bitwise_and(edges, mask) line_image = np.copy(image)*0 # Run Hough on edge detected image # Output "lines" is an array containing endpoints of detected line segments lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap) # Iterate over the output "lines" and draw lines on a blank image for line in lines: for x1,y1,x2,y2 in line: cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10) # Create a "color" binary image to combine with line image color_edges = np.dstack((edges, edges, edges)) # Draw the lines on the edge image lines_edges = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0) return lines_edges