Python cv2.drawContours() Examples
The following are 30
code examples of cv2.drawContours().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cv2
, or try the search function
.
Example #1
Source File: generate_coco_json.py From coco-json-converter with GNU General Public License v3.0 | 14 votes |
def __get_annotation__(self, mask, image=None): _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) segmentation = [] for contour in contours: # Valid polygons have >= 6 coordinates (3 points) if contour.size >= 6: segmentation.append(contour.flatten().tolist()) RLEs = cocomask.frPyObjects(segmentation, mask.shape[0], mask.shape[1]) RLE = cocomask.merge(RLEs) # RLE = cocomask.encode(np.asfortranarray(mask)) area = cocomask.area(RLE) [x, y, w, h] = cv2.boundingRect(mask) if image is not None: image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) cv2.drawContours(image, contours, -1, (0,255,0), 1) cv2.rectangle(image,(x,y),(x+w,y+h), (255,0,0), 2) cv2.imshow("", image) cv2.waitKey(1) return segmentation, [x, y, w, h], area
Example #2
Source File: thresholding.py From smashscan with MIT License | 12 votes |
def contour_filter(self, frame): _, contours, _ = cv2.findContours(frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) new_frame = np.zeros(frame.shape, np.uint8) for i, contour in enumerate(contours): c_area = cv2.contourArea(contour) if self.contour_min_area <= c_area <= self.contour_max_area: mask = np.zeros(frame.shape, np.uint8) cv2.drawContours(mask, contours, i, 255, cv2.FILLED) mask = cv2.bitwise_and(frame, mask) new_frame = cv2.bitwise_or(new_frame, mask) frame = new_frame if self.contour_disp_flag: frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR) cv2.drawContours(frame, contours, -1, (255, 0, 0), 1) return frame # A number of methods corresponding to the various trackbars available.
Example #3
Source File: pycv2.py From vrequest with MIT License | 8 votes |
def canny(filepathname, left=70, right=140): v = cv2.imread(filepathname) s = cv2.cvtColor(v, cv2.COLOR_BGR2GRAY) s = cv2.Canny(s, left, right) cv2.imshow('nier',s) return s # 圈出最小方矩形框,这里Canny算法后都是白色线条,所以取色范围 127-255 即可。 # ret, binary = cv2.threshold(s,127,255,cv2.THRESH_BINARY) # contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # for c in contours: # x,y,w,h = cv2.boundingRect(c) # if w>5 and h>10: # 有约束的画框 # cv2.rectangle(v,(x,y),(x+w,y+h),(155,155,0),1) # # cv2.drawContours(s,contours,-1,(0,0,255),3) # 画所有框 # cv2.imshow('nier2',v) # cv2.waitKey() # cv2.destroyAllWindows()
Example #4
Source File: helpers.py From DEXTR-KerasTensorflow with GNU General Public License v3.0 | 7 votes |
def overlay_masks(im, masks, alpha=0.5): colors = np.load(os.path.join(os.path.dirname(__file__), 'pascal_map.npy'))/255. if isinstance(masks, np.ndarray): masks = [masks] assert len(colors) >= len(masks), 'Not enough colors' ov = im.copy() im = im.astype(np.float32) total_ma = np.zeros([im.shape[0], im.shape[1]]) i = 1 for ma in masks: ma = ma.astype(np.bool) fg = im * alpha+np.ones(im.shape) * (1 - alpha) * colors[i, :3] # np.array([0,0,255])/255.0 i = i + 1 ov[ma == 1] = fg[ma == 1] total_ma += ma # [-2:] is s trick to be compatible both with opencv 2 and 3 contours = cv2.findContours(ma.copy().astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:] cv2.drawContours(ov, contours[0], -1, (0.0, 0.0, 0.0), 1) ov[total_ma == 0] = im[total_ma == 0] return ov
Example #5
Source File: vis.py From Parsing-R-CNN with MIT License | 7 votes |
def vis_mask(img, mask, bbox_color, show_parss=False): """Visualizes a single binary mask.""" img = img.astype(np.float32) idx = np.nonzero(mask) border_color = cfg.VIS.SHOW_SEGMS.BORDER_COLOR border_thick = cfg.VIS.SHOW_SEGMS.BORDER_THICK mask_color = bbox_color if cfg.VIS.SHOW_SEGMS.MASK_COLOR_FOLLOW_BOX else _WHITE mask_color = np.asarray(mask_color) mask_alpha = cfg.VIS.SHOW_SEGMS.MASK_ALPHA _, contours, _ = cv2.findContours(mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) if cfg.VIS.SHOW_SEGMS.SHOW_BORDER: cv2.drawContours(img, contours, -1, border_color, border_thick, cv2.LINE_AA) if cfg.VIS.SHOW_SEGMS.SHOW_MASK and not show_parss: img[idx[0], idx[1], :] *= 1.0 - mask_alpha img[idx[0], idx[1], :] += mask_alpha * mask_color return img.astype(np.uint8)
Example #6
Source File: vis.py From Parsing-R-CNN with MIT License | 7 votes |
def vis_parsing(img, parsing, colormap, show_segms=True): """Visualizes a single binary parsing.""" img = img.astype(np.float32) idx = np.nonzero(parsing) parsing_alpha = cfg.VIS.SHOW_PARSS.PARSING_ALPHA colormap = colormap_utils.dict2array(colormap) parsing_color = colormap[parsing.astype(np.int)] border_color = cfg.VIS.SHOW_PARSS.BORDER_COLOR border_thick = cfg.VIS.SHOW_PARSS.BORDER_THICK img[idx[0], idx[1], :] *= 1.0 - parsing_alpha # img[idx[0], idx[1], :] += alpha * parsing_color img += parsing_alpha * parsing_color if cfg.VIS.SHOW_PARSS.SHOW_BORDER and not show_segms: _, contours, _ = cv2.findContours(parsing.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) cv2.drawContours(img, contours, -1, border_color, border_thick, cv2.LINE_AA) return img.astype(np.uint8)
Example #7
Source File: page_dewarp.py From page_dewarp with MIT License | 6 votes |
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)
Example #8
Source File: visualize.py From ExtremeNet with BSD 3-Clause "New" or "Revised" License | 6 votes |
def vis_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=2): """Visualizes a single binary mask.""" img = img.astype(np.float32) idx = np.nonzero(mask) img[idx[0], idx[1], :] *= 1.0 - alpha img[idx[0], idx[1], :] += alpha * col if show_border: # How to use `cv2.findContours` in different OpenCV versions? # https://stackoverflow.com/questions/48291581/how-to-use-cv2-findcontours-in-different-opencv-versions/48292371#48292371 contours = cv2.findContours( mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)[-2] cv2.drawContours(img, contours, -1, _WHITE, border_thick, cv2.LINE_AA) return img.astype(np.uint8)
Example #9
Source File: predictor.py From DetNAS with MIT License | 6 votes |
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `labels`. """ masks = predictions.get_field("mask").numpy() labels = predictions.get_field("labels") colors = self.compute_colors_for_labels(labels).tolist() for mask, color in zip(masks, colors): thresh = mask[0, :, :, None] contours, hierarchy = cv2_util.findContours( thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) image = cv2.drawContours(image, contours, -1, color, 3) composite = image return composite
Example #10
Source File: page_dewarp.py From page_dewarp with MIT License | 6 votes |
def visualize_spans(name, small, pagemask, spans): regions = np.zeros_like(small) for i, span in enumerate(spans): contours = [cinfo.contour for cinfo in span] cv2.drawContours(regions, contours, -1, CCOLORS[i*3 % len(CCOLORS)], -1) mask = (regions.max(axis=2) != 0) display = small.copy() display[mask] = (display[mask]/2) + (regions[mask]/2) display[pagemask == 0] /= 4 debug_show(name, 2, 'spans', display)
Example #11
Source File: predictor.py From R2CNN.pytorch with MIT License | 6 votes |
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `labels`. """ masks = predictions.get_field("mask").numpy() labels = predictions.get_field("labels") colors = self.compute_colors_for_labels(labels).tolist() for mask, color in zip(masks, colors): thresh = mask[0, :, :, None] contours, hierarchy = cv2_util.findContours( thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) image = cv2.drawContours(image, contours, -1, color, 3) composite = image return composite
Example #12
Source File: predictor.py From remote_sensing_object_detection_2019 with MIT License | 6 votes |
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `labels`. """ masks = predictions.get_field("mask").numpy() labels = predictions.get_field("labels") colors = self.compute_colors_for_labels(labels).tolist() for mask, color in zip(masks, colors): thresh = mask[0, :, :, None] contours, hierarchy = cv2_util.findContours( thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) image = cv2.drawContours(image, contours, -1, color, 3) composite = image return composite
Example #13
Source File: crop_morphology.py From Python-Code with MIT License | 6 votes |
def remove_border(contour, ary): """Remove everything outside a border contour.""" # Use a rotated rectangle (should be a good approximation of a border). # If it's far from a right angle, it's probably two sides of a border and # we should use the bounding box instead. c_im = np.zeros(ary.shape) r = cv2.minAreaRect(contour) degs = r[2] if angle_from_right(degs) <= 10.0: box = cv2.cv.BoxPoints(r) box = np.int0(box) cv2.drawContours(c_im, [box], 0, 255, -1) cv2.drawContours(c_im, [box], 0, 0, 4) else: x1, y1, x2, y2 = cv2.boundingRect(contour) cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1) cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4) return np.minimum(c_im, ary)
Example #14
Source File: data_preprocessing_autoencoder.py From AVSR-Deep-Speech with GNU General Public License v2.0 | 6 votes |
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)
Example #15
Source File: viz.py From Object_Detection_Tracking with Apache License 2.0 | 6 votes |
def draw_mask(im, mask, alpha=0.5, color=None, show_border=True,border_thick=1): """ Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically """ if color is None: color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1] im = np.where(np.squeeze(np.repeat((mask > 0)[:, :, None], 3, axis=2)), im * (1 - alpha) + color * alpha, im) if show_border: if cv2.__version__.startswith("2"): contours, _ = cv2.findContours(mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) else: # cv 3 _,contours, _ = cv2.findContours(mask.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) cv2.drawContours(im, contours, -1, (255,255,255), border_thick, lineType=cv2.CV_AA) im = im.astype('uint8') return im
Example #16
Source File: visualize.py From Color-Tracker with MIT License | 6 votes |
def draw_debug_frame_for_object(debug_frame, tracked_object: TrackedObject, color: Tuple[int, int, int] = (255, 255, 255)): # contour = tracked_object.last_object_contour bbox = tracked_object.last_bbox points = tracked_object.tracked_points # if contour is not None: # cv2.drawContours(debug_frame, [contour], -1, (0, 255, 0), cv2.FILLED) if bbox is not None: x1, y1, x2, y2 = bbox cv2.rectangle(debug_frame, (x1, y1), (x2, y2), (255, 255, 255), 1) cv2.putText(debug_frame, "Id {0}".format(tracked_object.id), (x1, y1 - 5), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255)) if points is not None and len(points) > 0: draw_tracker_points(points, debug_frame, color) cv2.circle(debug_frame, tuple(points[-1]), 3, (0, 0, 255), -1) return debug_frame
Example #17
Source File: predictor.py From Res2Net-maskrcnn with MIT License | 6 votes |
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `labels`. """ masks = predictions.get_field("mask").numpy() labels = predictions.get_field("labels") colors = self.compute_colors_for_labels(labels).tolist() for mask, color in zip(masks, colors): thresh = mask[0, :, :, None] contours, hierarchy = cv2_util.findContours( thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) image = cv2.drawContours(image, contours, -1, color, 3) composite = image return composite
Example #18
Source File: predictor.py From remote_sensing_object_detection_2019 with MIT License | 6 votes |
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `labels`. """ masks = predictions.get_field("mask").numpy() labels = predictions.get_field("labels") colors = self.compute_colors_for_labels(labels).tolist() for mask, color in zip(masks, colors): thresh = mask[0, :, :, None] contours, hierarchy = cv2_util.findContours( thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) image = cv2.drawContours(image, contours, -1, color, 3) composite = image return composite
Example #19
Source File: detect_tables.py From namsel with MIT License | 6 votes |
def find_boxes(tiff_fl, blur=False): im = Image.open(tiff_fl).convert('L') a = np.asarray(im) if blur: a = cv.GaussianBlur(a, (5, 5), 0) contours, hierarchy = cv.findContours(a.copy(), mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_SIMPLE) border_boxes = [] # n = np.ones_like(a) for j,cnt in enumerate(contours): cnt_len = cv.arcLength(cnt, True) orig_cnt = cnt.copy() cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True) if len(cnt) == 4 and ((a.shape[0]-3) * (a.shape[1] -3)) > cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt): cnt = cnt.reshape(-1, 2) max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)]) if max_cos < 0.1: b = cv.boundingRect(orig_cnt) x,y,w,h = b border_boxes.append(b) # cv.rectangle(n, (x,y), (x+w, y+h), 0) # cv.drawContours(n, [cnt], -1,0, thickness = 5) # Image.fromarray(n*255).show() return border_boxes
Example #20
Source File: Dataloader.py From Text_Segmentation_Image_Inpainting with GNU General Public License v3.0 | 6 votes |
def draw_contour(img, mask): a, b, c = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) for cnt in b: approx = cv2.approxPolyDP(cnt, 0, True) cv2.drawContours(img, [approx], 0, (255, 255, 255), -1) return img
Example #21
Source File: predictor.py From argoverse_baselinetracker with MIT License | 6 votes |
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `labels`. """ masks = predictions.get_field("mask").numpy() labels = predictions.get_field("labels") colors = self.compute_colors_for_labels(labels).tolist() for mask, color in zip(masks, colors): thresh = mask[0, :, :, None] contours, hierarchy = cv2_util.findContours( thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) image = cv2.drawContours(image, contours, -1, color, 3) composite = image return composite
Example #22
Source File: CThermal.py From Thermal_Image_Analysis with MIT License | 6 votes |
def get_roi(thermal_image, thermal_np, raw_thermal_np, Contours, index, area_rect = None ): raw_roi_values = [] thermal_roi_values = [] indices = [] if area_rect is None: img2 = np.zeros( (thermal_image.shape[0], thermal_image.shape[1],1), np.uint8) cv.drawContours(img2 , Contours , index, 255 , -1 ) x,y,w,h = cv.boundingRect(Contours[index]) indices = np.arange(w*h) ind = np.where(img2[:, :, 0] == 255) indices = indices[np.where(img2[y:y+h,x:x+w,0].flatten() == 255)] raw_roi_values = raw_thermal_np[ind] thermal_roi_values = thermal_np[ind] else: x,y,w,h = area_rect raw_roi_values = raw_thermal_np[y:y+h, x:x+w] thermal_roi_values = thermal_np[y:y+h, x:x+w] return raw_roi_values, thermal_roi_values, indices
Example #23
Source File: TrainTestD.py From Text-Recognition with GNU Lesser General Public License v2.1 | 6 votes |
def check_show_f(self, d_name, path, contour, data, target, link): import matplotlib.pyplot as plt import cv2 print(d_name[0], path[0], contour[0].shape) show_t = np.zeros([data[0].shape[2], data[0].shape[3], 3]) show_t[:, :, 0] = target[0][0].data.cpu().numpy().transpose(1, 2, 0)[:, :, 0] show_l = np.zeros([data[0].shape[2], data[0].shape[3], 3]) show_l[:, :, 0] = link[0][0].data.cpu().numpy().transpose(1, 2, 0)[:, :, 0] image = (data[0][0].data.cpu().numpy().transpose(1, 2, 0)*255).astype(np.uint8).copy() cv2.drawContours(image, np.array(contour[0]).astype(np.int32), -1, (0, 255, 0), 3) plt.imshow(np.concatenate((data[0][0].data.cpu().numpy().transpose(1, 2, 0), show_t, show_l), axis=1)) plt.show() plt.imshow(data[0][0].data.cpu().numpy().transpose(1, 2, 0)*show_t) plt.show() plt.imshow(image) plt.show()
Example #24
Source File: crop_morphology.py From oldnyc with Apache License 2.0 | 6 votes |
def remove_border(contour, ary): """Remove everything outside a border contour.""" # Use a rotated rectangle (should be a good approximation of a border). # If it's far from a right angle, it's probably two sides of a border and # we should use the bounding box instead. c_im = np.zeros(ary.shape) r = cv2.minAreaRect(contour) degs = r[2] if angle_from_right(degs) <= 10.0: box = cv2.cv.BoxPoints(r) box = np.int0(box) cv2.drawContours(c_im, [box], 0, 255, -1) cv2.drawContours(c_im, [box], 0, 0, 4) else: x1, y1, x2, y2 = cv2.boundingRect(contour) cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1) cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4) return np.minimum(c_im, ary)
Example #25
Source File: scale_two.py From Text-Recognition with GNU Lesser General Public License v2.1 | 6 votes |
def _custom_get(self, i, no, all_returns): for dataset_name, d in self.datasets_attr.items(): if d['range'][0] <= i and d['range'][1] > i: image_root = d['image_root'] d_name = dataset_name break image_new, link_new, target_new, weight_new, contour_i = self.aspect_resize(self.loader(image_root+'/'+self.images[i]), self.annots[i].copy(), self.remove_annots[i].copy())#, big_target_new image_new, target_new, link_new, contour_i = self.rotate(image_new, target_new, link_new, contour_i, 90) show = True if show: plt.imsave('img.png',image_new) num = np.array(image_new) cv2.drawContours(num, contour_i, -1, (0,255,0), 3) plt.imsave('contours.png',num) plt.imsave('target.png',target_new) img = self.transform(image_new).unsqueeze(0) target = self.target_transform(target_new).unsqueeze(0) link = self.target_transform(link_new).unsqueeze(0) weight = torch.FloatTensor(weight_new).unsqueeze(0).unsqueeze(0) all_returns[no] = [img, target, link, weight, contour_i, d_name]
Example #26
Source File: predictor.py From remote_sensing_object_detection_2019 with MIT License | 6 votes |
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `labels`. """ masks = predictions.get_field("mask").numpy() labels = predictions.get_field("labels") colors = self.compute_colors_for_labels(labels).tolist() for mask, color in zip(masks, colors): thresh = mask[0, :, :, None] contours, hierarchy = cv2_util.findContours( thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) image = cv2.drawContours(image, contours, -1, color, 3) composite = image return composite
Example #27
Source File: postprocessing.py From open-solution-ship-detection with MIT License | 5 votes |
def mask_to_bbox(mask): img_box = np.zeros_like(mask) _, cnt, _ = cv2.findContours(mask, 1, 2) rect = cv2.minAreaRect(cnt[0]) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img_box, [box], 0, 1, -1) return img_box
Example #28
Source File: capdet.py From katarina with MIT License | 5 votes |
def detectTwoColors( img, capColors ): imgResult = np.zeros( img.shape, np.uint8 ) imgB, imgG, imgR = cv2.split(img) for col in capColors: maskB = np.logical_and( imgB < col[0]+rad, imgB > col[0]-rad ) maskG = np.logical_and( imgG < col[1]+rad, imgG > col[1]-rad ) maskR = np.logical_and( imgR < col[2]+rad, imgR > col[2]-rad ) mask = np.logical_and(maskR, maskG) mask = np.logical_and(mask, maskB) if col[1] > max(col[0],col[2]): imgResult[mask] = (0,255,0) # green else: imgResult[mask] = (0,128,255) # orange gray = cv2.cvtColor( imgResult, cv2.COLOR_BGR2GRAY ) ret, binary = cv2.threshold( gray, 1, 255, cv2.THRESH_BINARY ) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)) binary = cv2.dilate( binary, kernel ) cmpRG = imgR > imgG contours, hierarchy = cv2.findContours( binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) result = [] for cnt in contours: area = cv2.contourArea(cnt, oriented=True) if area < 0: cv2.drawContours(imgResult, [cnt], -1, (255,0,0), 2) maskTmp = np.zeros( (img.shape[0],img.shape[1]), np.uint8 ) cv2.drawContours(maskTmp, [cnt], -1, 255, -1) mask = maskTmp > 0 orange = np.count_nonzero(np.logical_and( mask, cmpRG )) # print abs(area), orange, orange/float(abs(area)) frac = orange/float(abs(area)) if abs(area) > 20 and (0.4 < frac < 0.7): M = cv2.moments(cnt) cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) result.append( ((cx,cy), int(abs(area)), int(orange)) ) return imgResult, result
Example #29
Source File: transforms.py From PolarMask with Apache License 2.0 | 5 votes |
def bbox_mask2result(bboxes, masks, labels, num_classes, img_meta): """Convert detection results to a list of numpy arrays. Args: bboxes (Tensor): shape (n, 5) masks (Tensor): shape (n, 2, 36) labels (Tensor): shape (n, ) num_classes (int): class number, including background class Returns: list(ndarray): bbox results of each class """ ori_shape = img_meta['ori_shape'] img_h, img_w, _ = ori_shape mask_results = [[] for _ in range(num_classes - 1)] for i in range(masks.shape[0]): im_mask = np.zeros((img_h, img_w), dtype=np.uint8) mask = [masks[i].transpose(1,0).unsqueeze(1).int().data.cpu().numpy()] im_mask = cv2.drawContours(im_mask, mask, -1,1,-1) rle = mask_util.encode( np.array(im_mask[:, :, np.newaxis], order='F'))[0] label = labels[i] mask_results[label].append(rle) if bboxes.shape[0] == 0: bbox_results = [ np.zeros((0, 5), dtype=np.float32) for i in range(num_classes - 1) ] return bbox_results, mask_results else: bboxes = bboxes.cpu().numpy() labels = labels.cpu().numpy() bbox_results = [bboxes[labels == i, :] for i in range(num_classes - 1)] return bbox_results, mask_results
Example #30
Source File: image_functions.py From niryo_one_ros with GNU General Public License v3.0 | 5 votes |
def draw_contours(img, contours): """ Draw a list of contour on an image and return the drawing image :param img: Image :param contours: contours list :return: Image with drawing """ if len(img.shape) == 2: img_bgr = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) else: img_bgr = img.copy() cv2.drawContours(img_bgr, contours, -1, (255, 0, 0), 3) return img_bgr