Python cv2.distanceTransform() Examples
The following are 24
code examples of cv2.distanceTransform().
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: web.py From Tabulo with BSD 3-Clause "New" or "Revised" License | 7 votes |
def get_image(): image = request.files.get('image') if not image: raise ValueError basewidth = 300 #wpercent = (basewidth/float(Image.open(image.stream).size[0])) #hsize = int((float(Image.open(image.stream).size[1])*float(wpercent))) img = Image.open(image.stream).convert('RGB') img = np.asarray(img) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) b = cv2.distanceTransform(img, distanceType=cv2.DIST_L2, maskSize=5) g = cv2.distanceTransform(img, distanceType=cv2.DIST_L1, maskSize=5) r = cv2.distanceTransform(img, distanceType=cv2.DIST_C, maskSize=5) # merge the transformed channels back to an image transformed_image = cv2.merge((b, g, r)) return transformed_image
Example #2
Source File: web.py From Table-Detection-using-Deep-learning with BSD 3-Clause "New" or "Revised" License | 7 votes |
def get_image(): image = request.files.get('image') if not image: raise ValueError img = Image.open(image.stream).convert('RGB') img = np.asarray(img) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) b = cv2.distanceTransform(img, distanceType=cv2.DIST_L2, maskSize=5) g = cv2.distanceTransform(img, distanceType=cv2.DIST_L1, maskSize=5) r = cv2.distanceTransform(img, distanceType=cv2.DIST_C, maskSize=5) # merge the transformed channels back to an image transformed_image = cv2.merge((b, g, r)) return transformed_image
Example #3
Source File: gui_draw.py From iGAN with MIT License | 6 votes |
def shadow_image(self, img, pos): if img is None: return None weighted_img = np.ones((img.shape[0], img.shape[1]), np.uint8) x = int(pos.x() / self.scale) y = int(pos.y() / self.scale) weighted_img[y, x] = 0 dist_img = cv2.distanceTransform(weighted_img, distanceType=cv2.cv.CV_DIST_L2, maskSize=5).astype(np.float32) dist_sigma = self.img_size/2.0 dist_img_f = np.exp(-dist_img / dist_sigma) dist_img_f = np.tile(dist_img_f[..., np.newaxis], [1,1,3]) l = 0.25 img_f = img.astype(np.float32) rst_f = (img_f * l + (1-l) * (img_f * dist_img_f + (1-dist_img_f)*255.0)) rst = rst_f.astype(np.uint8) return rst
Example #4
Source File: gangate_draw.py From iSketchNFill with GNU General Public License v3.0 | 6 votes |
def shadow_image(self, img, pos): if img is None: return None weighted_img = np.ones((img.shape[0], img.shape[1]), np.uint8) x = int(pos.x() / self.scale) y = int(pos.y() / self.scale) weighted_img[y, x] = 0 dist_img = cv2.distanceTransform(weighted_img, distanceType=cv2.cv.CV_DIST_L2, maskSize=5).astype(np.float32) dist_sigma = self.img_size/2.0 dist_img_f = np.exp(-dist_img / dist_sigma) dist_img_f = np.tile(dist_img_f[..., np.newaxis], [1,1,3]) l = 0.25 img_f = img.astype(np.float32) rst_f = (img_f * l + (1-l) * (img_f * dist_img_f + (1-dist_img_f)*255.0)) rst = rst_f.astype(np.uint8) return rst
Example #5
Source File: border.py From swiftnet with GNU General Public License v3.0 | 6 votes |
def __call__(self, example): labels = np.array(example['labels']) present_classes = np.unique(labels) distances = np.zeros([self.num_classes] + list(labels.shape), dtype=np.float32) - 1. for i in range(self.num_classes): if i not in present_classes: continue class_mask = labels == i distances[i][class_mask] = cv2.distanceTransform(np.uint8(class_mask), cv2.DIST_L2, maskSize=5)[class_mask] if self.reduce: ignore_mask = labels == self.ignore_id distances[distances < 0] = 0 distances = distances.sum(axis=0) label_distance_bins = np.digitize(distances, self.bins) label_distance_alphas = np.zeros(label_distance_bins.shape, dtype=np.float32) for idx, alpha in enumerate(self.alphas): label_distance_alphas[label_distance_bins == idx] = alpha label_distance_alphas[ignore_mask] = 0 example['label_distance_alphas'] = label_distance_alphas else: example['label_distance_transform'] = distances return example
Example #6
Source File: iou_util.py From SCCvSD with BSD 2-Clause "Simplified" License | 5 votes |
def ut_generate_grassland_mask(): # An example of generate soft mask for grassland segmentation import scipy.io as sio index = 16 - 1 # image index from 1 data = sio.loadmat('../../data/UoT_soccer/train_val.mat') annotation = data['annotation'] homo = annotation[0][index][1] # ground truth homography # step 1: generate a 'hard' grass mask template_h = 74 template_w = 115 tempalte_im = np.ones((template_h, template_w, 1), dtype=np.uint8) * 255 grass_mask = IouUtil.homography_warp(homo, tempalte_im, (1280, 720), (0)); cv.imshow('grass mask', grass_mask) cv.waitKey(0) # step 2: generate a 'soft' grass mask dist_threshold = 30 # change this value to change mask boundary _, binary_im = cv.threshold(grass_mask, 10, 255, cv.THRESH_BINARY_INV) dist_im = cv.distanceTransform(binary_im, cv.DIST_L2, cv.DIST_MASK_PRECISE) dist_im[dist_im > dist_threshold] = dist_threshold soft_mask = 1.0 - dist_im / dist_threshold # normalize to [0, 1] cv.imshow('soft mask', soft_mask) cv.waitKey(0) # step 3: soft mask on the original image stacked_mask = np.stack((soft_mask,) * 3, axis=-1) im = cv.imread('../../data/16.jpg') soft_im = cv.multiply(stacked_mask, im.astype(np.float32)).astype(np.uint8) cv.imshow('soft masked image', soft_im) cv.waitKey(0)
Example #7
Source File: synthetic_util.py From SCCvSD with BSD 2-Clause "Simplified" License | 5 votes |
def distance_transform(img): """ :param img: OpenCV Image :return: """ h, w, c = img.shape if c == 3: img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) else: assert c == 1 _, binary_im = cv.threshold(img, 10, 255, cv.THRESH_BINARY_INV) dist_im = cv.distanceTransform(binary_im, cv.DIST_L2, cv.DIST_MASK_PRECISE) return dist_im
Example #8
Source File: border.py From swiftnet with GNU General Public License v3.0 | 5 votes |
def __call__(self, example): shape = [self.instance_classes] + list(example['labels'].size)[::-1] instance_borders = np.zeros(shape, dtype=np.float32) instances = example['instances'] for k in instances: for instance in instances[k]: dist_trans = cv2.distanceTransform(instance.astype(np.uint8), cv2.DIST_L2, maskSize=5) dist_trans[instance] = 1. / dist_trans[instance] dist_trans[dist_trans < self.thresh] = .0 instance_borders[k] += dist_trans example['instance_borders'] = instance_borders return example
Example #9
Source File: mask_morphology.py From NucleiDetectron with Apache License 2.0 | 5 votes |
def opencv_segmentation(mask, kernel=k_3x3, k=3): # noise removal opening = cv.morphologyEx(mask, cv.MORPH_OPEN, kernel, iterations=k) # sure background area sure_bg = cv.dilate(opening, kernel, iterations=k) # Finding sure foreground area dist_transform = cv.distanceTransform(opening,cv.DIST_L2, 5) ret, sure_fg = cv.threshold(dist_transform, 0.7*dist_transform.max(), 255, 0) # Finding unknown region sure_fg = np.uint8(sure_fg) unknown = cv.subtract(sure_bg, sure_fg) # Marker labelling ret, markers = cv.connectedComponents(sure_fg) # Add one to all labels so that sure background is not 0, but 1 markers = markers + 1 # Now, mark the region of unknown with zero markers[unknown > 0] = 0 labels_ws = cv.watershed(cv.cvtColor(mask, cv.COLOR_GRAY2RGB), markers) if labels_ws.max() - 1 < 2: return [mask], labels_ws res_masks = [] for idx in range(2, labels_ws.max() + 1): m = labels_ws == idx if m.sum() > 5: m = cv.dilate(m.astype(np.uint8), kernel, iterations=1) res_masks.append(m) return res_masks, labels_ws
Example #10
Source File: exposure_correction.py From exposure_correction with MIT License | 5 votes |
def main(): # img = cv2.imread("test_img.JPG", 0) img = np.ones((600, 600)) adj_matrix = get_unweighted_adjacency(img) # print adj_matrix[0, 1] # cv2.namedWindow("output") # dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5) # ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)
Example #11
Source File: utils.py From eccv18-rgb_pose_refinement with MIT License | 5 votes |
def distance_transform(depth): """ Returns a distance transform for a depth map. :param depth: Zero values are exterior, non-zero values are interior area :return: The distance transform, signed and unsigned """ mask = (depth > 0).astype(np.float32) eroded = cv2.erode(mask, np.ones((3, 3), np.uint8)) contours = mask*(1-eroded) dt_unsigned = cv2.distanceTransform((1-contours).astype(np.uint8), cv2.DIST_L2, 3) dt_signed = np.copy(dt_unsigned) dt_signed[eroded.astype(bool)] = -dt_signed[eroded.astype(bool)] return dt_unsigned, dt_signed
Example #12
Source File: fake_util.py From CRAFT_keras with Apache License 2.0 | 5 votes |
def watershed(src): """ Performs a marker-based image segmentation using the watershed algorithm. :param src: 8-bit 1-channel image. :return: 32-bit single-channel image (map) of markers. """ # cv2.imwrite('{}.png'.format(np.random.randint(1000)), src) gray = src.copy() img = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) # h, w = gray.shape[:2] # block_size = (min(h, w) // 4 + 1) * 2 + 1 # thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, block_size, 0) _ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # noise removal kernel = np.ones((3, 3), np.uint8) opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2) # sure background area sure_bg = cv2.dilate(opening, kernel, iterations=3) # Finding sure foreground area dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5) # dist_transform = opening & gray # cv2.imshow('dist_transform', dist_transform) # _ret, sure_bg = cv2.threshold(dist_transform, 0.2 * dist_transform.max(), 255, cv2.THRESH_BINARY_INV) _ret, sure_fg = cv2.threshold(dist_transform, 0.2 * dist_transform.max(), 255, cv2.THRESH_BINARY) # Finding unknown region # sure_bg = np.uint8(sure_bg) sure_fg = np.uint8(sure_fg) # cv2.imshow('sure_fg', sure_fg) unknown = cv2.subtract(sure_bg, sure_fg) # Marker label lingret, marker_map = cv2.connectedComponents(sure_fg) # Add one to all labels so that sure background is not 0, but 1 marker_map = marker_map + 1 # Now, mark the region of unknown with zero marker_map[unknown == 255] = 0 marker_map = cv2.watershed(img, marker_map) return marker_map
Example #13
Source File: utils.py From DeepGrabCut-PyTorch with MIT License | 5 votes |
def compute_dismap(dismap, bbox): x_min, y_min, x_max, y_max = bbox[:] # draw bounding box cv2.line(dismap, (x_min, y_min), (x_max, y_min), color=1, thickness=1) cv2.line(dismap, (x_min, y_min), (x_min, y_max), color=1, thickness=1) cv2.line(dismap, (x_max, y_max), (x_max, y_min), color=1, thickness=1) cv2.line(dismap, (x_max, y_max), (x_min, y_max), color=1, thickness=1) tmp = (dismap > 0).astype(np.uint8) # mark boundary tmp_ = deepcopy(tmp) fill_mask = np.ones((tmp.shape[0] + 2, tmp.shape[1] + 2)).astype(np.uint8) fill_mask[1:-1, 1:-1] = tmp_ cv2.floodFill(tmp_, fill_mask, (int((x_min + x_max) / 2), int((y_min + y_max) / 2)), 5) # fill pixel inside bounding box tmp_ = tmp_.astype(np.int8) tmp_[tmp_ == 5] = -1 # pixel inside bounding box tmp_[tmp_ == 0] = 1 # pixel on and outside bounding box tmp = (tmp == 0).astype(np.uint8) dismap = cv2.distanceTransform(tmp, cv2.DIST_L2, cv2.DIST_MASK_PRECISE) # compute distance inside and outside bounding box dismap = tmp_ * dismap + 128 dismap[dismap > 255] = 255 dismap[dismap < 0] = 0 dismap = dismap.astype(np.uint8) return dismap
Example #14
Source File: distance_transform.py From plantcv with MIT License | 5 votes |
def distance_transform(bin_img, distance_type, mask_size): """Creates an image where for each object pixel, a number is assigned that corresponds to the distance to the nearest background pixel. Inputs: img = Binary image data distance_type = Type of distance. It can be CV_DIST_L1, CV_DIST_L2 , or CV_DIST_C which are 1, 2 and 3, respectively. mask_size = Size of the distance transform mask. It can be 3, 5, or CV_DIST_MASK_PRECISE (the latter option is only supported by the first function). In case of the CV_DIST_L1 or CV_DIST_C distance type, the parameter is forced to 3 because a 3 by 3 mask gives the same result as 5 by 5 or any larger aperture. Returns: norm_image = grayscale distance-transformed image normalized between [0, 1] :param bin_img: numpy.ndarray :param distance_type: int :param mask_size: int :return norm_image: numpy.ndarray """ params.device += 1 dist = cv2.distanceTransform(src=bin_img, distanceType=distance_type, maskSize=mask_size) norm_image = cv2.normalize(src=dist, dst=dist, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) if params.debug == 'print': print_image(norm_image, os.path.join(params.debug, str(params.device) + '_distance_transform.png')) elif params.debug == 'plot': plot_image(norm_image, cmap='gray') return norm_image
Example #15
Source File: img_to_jpeg.py From TableTrainNet with MIT License | 5 votes |
def uglify_image(pil_image): img = np.asarray(pil_image) img = cv2.distanceTransform(img, distanceType=cv2.DIST_L2, maskSize=5) return Image.fromarray(img).convert('L')
Example #16
Source File: core.py From soccerontable with BSD 2-Clause "Simplified" License | 5 votes |
def calibrate_from_initialization(img, mask, A_init, R_init, T_init, edge_sfactor=0.5, visualize=False): h, w = img.shape[:2] edges = image_utils.robust_edge_detection(cv2.resize(img, None, fx=edge_sfactor, fy=edge_sfactor)) edges = cv2.resize(edges, None, fx=1. / edge_sfactor, fy=1. / edge_sfactor) edges = cv2.Canny(edges.astype(np.uint8) * 255, 100, 200) / 255.0 mask = cv2.dilate(mask, np.ones((25, 25), dtype=np.uint8)) edges = edges * (1 - mask) dist_transf = cv2.distanceTransform((1 - edges).astype(np.uint8), cv2.DIST_L2, 0) cam_init = cam_utils.Camera('tmp', A_init, R_init, T_init, h, w) template, field_mask = draw_utils.draw_field(cam_init) II, JJ = (template > 0).nonzero() synth_field2d = np.array([[JJ, II]]).T[:, :, 0] field3d = cam_utils.plane_points_to_3d(synth_field2d, cam_init) A, R, T = _calibrate_camera_dist_transf(A_init, R_init, T_init, dist_transf, field3d) if visualize: cam_res = cam_utils.Camera('tmp', A, R, T, h, w) field2d, __ = cam_res.project(field3d) io.imshow(img, points=field2d) return A, R, T, field3d
Example #17
Source File: vis.py From Parsing-R-CNN with MIT License | 4 votes |
def vis_uv(img, uv, bbox): border_thick = cfg.VIS.SHOW_UV.BORDER_THICK grid_thick = cfg.VIS.SHOW_UV.GRID_THICK lines_num = cfg.VIS.SHOW_UV.LINES_NUM uv = np.transpose(uv, (1, 2, 0)) uv = cv2.resize(uv, (int(bbox[2] - bbox[0] + 1), int(bbox[3] - bbox[1] + 1)), interpolation=cv2.INTER_LINEAR) roi_img = img[int(bbox[1]):int(bbox[3] + 1), int(bbox[0]):int(bbox[2] + 1), :] roi_img_resize = cv2.resize(roi_img, (2 * roi_img.shape[1], 2 * roi_img.shape[0]), interpolation=cv2.INTER_LINEAR) I = uv[:, :, 0] for i in range(1, 25): if (len(I[I == i]) == 0): continue u = np.zeros_like(I) v = np.zeros_like(I) u[I == i] = uv[:, :, 1][I == i] v[I == i] = uv[:, :, 2][I == i] for ind in range(1, lines_num): thred = 1.0 * ind / lines_num _, thresh = cv2.threshold(u, u.min() + thred * (u.max() - u.min()), 255, 0) dist_transform = cv2.distanceTransform(np.uint8(thresh), cv2.DIST_L2, 0) dist_transform = np.uint8(dist_transform) _, contours, _ = cv2.findContours(dist_transform, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) contours = [(col * 2) for col in contours] cv2.drawContours(roi_img_resize, contours, -1, ((1 - thred) * 255, thred * 255, thred * 200), grid_thick) _, thresh = cv2.threshold(v, v.min() + thred * (v.max() - v.min()), 255, 0) dist_transform = cv2.distanceTransform(np.uint8(thresh), cv2.DIST_L2, 0) dist_transform = np.uint8(dist_transform) _, contours, _ = cv2.findContours(dist_transform, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) contours = [(col * 2) for col in contours] cv2.drawContours(roi_img_resize, contours, -1, (thred * 255, (1 - thred) * 255, thred * 200), grid_thick) _, thresh = cv2.threshold(I, 0.5, 255, 0) dist_transform = cv2.distanceTransform(np.uint8(thresh), cv2.DIST_L2, 0) dist_transform = np.uint8(dist_transform) _, contours, _ = cv2.findContours(dist_transform, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) contours = [(col * 2) for col in contours] cv2.drawContours(roi_img_resize, contours, -1, (70, 150, 0), border_thick) roi_img[:] = cv2.resize(roi_img_resize, (roi_img.shape[1], roi_img.shape[0]), interpolation=cv2.INTER_LINEAR)[:] return img
Example #18
Source File: watershed.py From python-image-processing with MIT License | 4 votes |
def watershed(src): # Change color to gray scale gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) # Use the Otsu's binarization thresh,bin_img = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # print(thresh) # print threshold # Noise removal kernel = np.ones((3,3), np.uint8) opening = cv2.morphologyEx(bin_img,cv2.MORPH_OPEN,kernel,iterations = 2) # Sure background area sure_bg = cv2.dilate(opening,kernel,iterations=3) # Finding sure foreground area dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5) ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0) # Finding unknown region sure_fg = np.uint8(sure_fg) unknown = cv2.subtract(sure_bg,sure_fg) # Marker labelling ret, markers = cv2.connectedComponents(sure_fg) # Add one to all labels so that sure background is not 0, but 1 markers = markers+1 # Now, mark the region of unknown with zero markers[unknown==255] = 0 # Apply watershed markers = cv2.watershed(src,markers) src[markers == -1] = [255,0,0] # Check marker (If check markers, please import matplotlib) # plt.imshow(markers) # plt.show() # Check markers data # print(np.unique(markers,return_counts=True)) return markers, src
Example #19
Source File: make_tinyimagenet_c.py From robustness with Apache License 2.0 | 4 votes |
def spatter(x, severity=1): c = [(0.62,0.1,0.7,0.7,0.6,0), (0.65,0.1,0.8,0.7,0.6,0), (0.65,0.3,1,0.69,0.6,0), (0.65,0.1,0.7,0.68,0.6,1), (0.65,0.1,0.5,0.67,0.6,1)][severity - 1] x = np.array(x, dtype=np.float32) / 255. liquid_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1]) liquid_layer = gaussian(liquid_layer, sigma=c[2]) liquid_layer[liquid_layer < c[3]] = 0 if c[5] == 0: liquid_layer = (liquid_layer * 255).astype(np.uint8) dist = 255 - cv2.Canny(liquid_layer, 50, 150) dist = cv2.distanceTransform(dist, cv2.DIST_L2, 5) _, dist = cv2.threshold(dist, 20, 20, cv2.THRESH_TRUNC) dist = cv2.blur(dist, (3, 3)).astype(np.uint8) dist = cv2.equalizeHist(dist) # ker = np.array([[-1,-2,-3],[-2,0,0],[-3,0,1]], dtype=np.float32) # ker -= np.mean(ker) ker = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]]) dist = cv2.filter2D(dist, cv2.CV_8U, ker) dist = cv2.blur(dist, (3, 3)).astype(np.float32) m = cv2.cvtColor(liquid_layer * dist, cv2.COLOR_GRAY2BGRA) m /= np.max(m, axis=(0, 1)) m *= c[4] # water is pale turqouise color = np.concatenate((175 / 255. * np.ones_like(m[..., :1]), 238 / 255. * np.ones_like(m[..., :1]), 238 / 255. * np.ones_like(m[..., :1])), axis=2) color = cv2.cvtColor(color, cv2.COLOR_BGR2BGRA) x = cv2.cvtColor(x, cv2.COLOR_BGR2BGRA) return cv2.cvtColor(np.clip(x + m * color, 0, 1), cv2.COLOR_BGRA2BGR) * 255 else: m = np.where(liquid_layer > c[3], 1, 0) m = gaussian(m.astype(np.float32), sigma=c[4]) m[m < 0.8] = 0 # m = np.abs(m) ** (1/c[4]) # mud brown color = np.concatenate((63 / 255. * np.ones_like(x[..., :1]), 42 / 255. * np.ones_like(x[..., :1]), 20 / 255. * np.ones_like(x[..., :1])), axis=2) color *= m[..., np.newaxis] x *= (1 - m[..., np.newaxis]) return np.clip(x + color, 0, 1) * 255
Example #20
Source File: corruptions.py From robustness with Apache License 2.0 | 4 votes |
def spatter(x, severity=1): c = [(0.65, 0.3, 4, 0.69, 0.6, 0), (0.65, 0.3, 3, 0.68, 0.6, 0), (0.65, 0.3, 2, 0.68, 0.5, 0), (0.65, 0.3, 1, 0.65, 1.5, 1), (0.67, 0.4, 1, 0.65, 1.5, 1)][severity - 1] x = np.array(x, dtype=np.float32) / 255. liquid_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1]) liquid_layer = gaussian(liquid_layer, sigma=c[2]) liquid_layer[liquid_layer < c[3]] = 0 if c[5] == 0: liquid_layer = (liquid_layer * 255).astype(np.uint8) dist = 255 - cv2.Canny(liquid_layer, 50, 150) dist = cv2.distanceTransform(dist, cv2.DIST_L2, 5) _, dist = cv2.threshold(dist, 20, 20, cv2.THRESH_TRUNC) dist = cv2.blur(dist, (3, 3)).astype(np.uint8) dist = cv2.equalizeHist(dist) ker = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]]) dist = cv2.filter2D(dist, cv2.CV_8U, ker) dist = cv2.blur(dist, (3, 3)).astype(np.float32) m = cv2.cvtColor(liquid_layer * dist, cv2.COLOR_GRAY2BGRA) m /= np.max(m, axis=(0, 1)) m *= c[4] # water is pale turqouise color = np.concatenate((175 / 255. * np.ones_like(m[..., :1]), 238 / 255. * np.ones_like(m[..., :1]), 238 / 255. * np.ones_like(m[..., :1])), axis=2) color = cv2.cvtColor(color, cv2.COLOR_BGR2BGRA) x = cv2.cvtColor(x, cv2.COLOR_BGR2BGRA) return cv2.cvtColor(np.clip(x + m * color, 0, 1), cv2.COLOR_BGRA2BGR) * 255 else: m = np.where(liquid_layer > c[3], 1, 0) m = gaussian(m.astype(np.float32), sigma=c[4]) m[m < 0.8] = 0 # mud brown color = np.concatenate((63 / 255. * np.ones_like(x[..., :1]), 42 / 255. * np.ones_like(x[..., :1]), 20 / 255. * np.ones_like(x[..., :1])), axis=2) color *= m[..., np.newaxis] x *= (1 - m[..., np.newaxis]) return np.clip(x + color, 0, 1) * 255
Example #21
Source File: plant_features.py From bonnet with GNU General Public License v3.0 | 4 votes |
def watershed(rgb, idx, mask): ''' Get watershed transform from image ''' # kernel definition kernel = np.ones((3, 3), np.uint8) # sure background area sure_bg = cv2.dilate(mask, kernel) sure_bg = np.uint8(sure_bg) # util.im_gray_plt(sure_bg,"sure back") # Finding sure foreground area dist_transform = cv2.distanceTransform(np.uint8(mask), cv2.DIST_L2, 3) # util.im_gray_plt(dist_transform,"dist transform") ret, sure_fg = cv2.threshold( dist_transform, 0.5 * dist_transform.max(), 255, 0) # Finding unknown region sure_fg = np.uint8(sure_fg) # util.im_gray_plt(sure_fg,"sure fore") unknown = cv2.subtract(sure_bg, sure_fg) # util.im_gray_plt(unknown,"unknown") # marker labelling ret, markers = cv2.connectedComponents(sure_fg) # add one to all labels so that sure background is not 0, but 1 markers = markers + 1 # mark the region of unknown with zero markers[unknown == 255] = 0 # util.im_gray_plt(np.uint8(markers),"markers") # apply watershed markers = cv2.watershed(rgb, markers) # create limit mask mask = np.zeros(mask.shape, np.uint8) mask[markers == -1] = 255 return mask
Example #22
Source File: make_imagenet_c.py From robustness with Apache License 2.0 | 4 votes |
def spatter(x, severity=1): c = [(0.65, 0.3, 4, 0.69, 0.6, 0), (0.65, 0.3, 3, 0.68, 0.6, 0), (0.65, 0.3, 2, 0.68, 0.5, 0), (0.65, 0.3, 1, 0.65, 1.5, 1), (0.67, 0.4, 1, 0.65, 1.5, 1)][severity - 1] x = np.array(x, dtype=np.float32) / 255. liquid_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1]) liquid_layer = gaussian(liquid_layer, sigma=c[2]) liquid_layer[liquid_layer < c[3]] = 0 if c[5] == 0: liquid_layer = (liquid_layer * 255).astype(np.uint8) dist = 255 - cv2.Canny(liquid_layer, 50, 150) dist = cv2.distanceTransform(dist, cv2.DIST_L2, 5) _, dist = cv2.threshold(dist, 20, 20, cv2.THRESH_TRUNC) dist = cv2.blur(dist, (3, 3)).astype(np.uint8) dist = cv2.equalizeHist(dist) # ker = np.array([[-1,-2,-3],[-2,0,0],[-3,0,1]], dtype=np.float32) # ker -= np.mean(ker) ker = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]]) dist = cv2.filter2D(dist, cv2.CV_8U, ker) dist = cv2.blur(dist, (3, 3)).astype(np.float32) m = cv2.cvtColor(liquid_layer * dist, cv2.COLOR_GRAY2BGRA) m /= np.max(m, axis=(0, 1)) m *= c[4] # water is pale turqouise color = np.concatenate((175 / 255. * np.ones_like(m[..., :1]), 238 / 255. * np.ones_like(m[..., :1]), 238 / 255. * np.ones_like(m[..., :1])), axis=2) color = cv2.cvtColor(color, cv2.COLOR_BGR2BGRA) x = cv2.cvtColor(x, cv2.COLOR_BGR2BGRA) return cv2.cvtColor(np.clip(x + m * color, 0, 1), cv2.COLOR_BGRA2BGR) * 255 else: m = np.where(liquid_layer > c[3], 1, 0) m = gaussian(m.astype(np.float32), sigma=c[4]) m[m < 0.8] = 0 # m = np.abs(m) ** (1/c[4]) # mud brown color = np.concatenate((63 / 255. * np.ones_like(x[..., :1]), 42 / 255. * np.ones_like(x[..., :1]), 20 / 255. * np.ones_like(x[..., :1])), axis=2) color *= m[..., np.newaxis] x *= (1 - m[..., np.newaxis]) return np.clip(x + color, 0, 1) * 255
Example #23
Source File: make_cifar_c.py From robustness with Apache License 2.0 | 4 votes |
def spatter(x, severity=1): c = [(0.62,0.1,0.7,0.7,0.5,0), (0.65,0.1,0.8,0.7,0.5,0), (0.65,0.3,1,0.69,0.5,0), (0.65,0.1,0.7,0.69,0.6,1), (0.65,0.1,0.5,0.68,0.6,1)][severity - 1] x = np.array(x, dtype=np.float32) / 255. liquid_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1]) liquid_layer = gaussian(liquid_layer, sigma=c[2]) liquid_layer[liquid_layer < c[3]] = 0 if c[5] == 0: liquid_layer = (liquid_layer * 255).astype(np.uint8) dist = 255 - cv2.Canny(liquid_layer, 50, 150) dist = cv2.distanceTransform(dist, cv2.DIST_L2, 5) _, dist = cv2.threshold(dist, 20, 20, cv2.THRESH_TRUNC) dist = cv2.blur(dist, (3, 3)).astype(np.uint8) dist = cv2.equalizeHist(dist) # ker = np.array([[-1,-2,-3],[-2,0,0],[-3,0,1]], dtype=np.float32) # ker -= np.mean(ker) ker = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]]) dist = cv2.filter2D(dist, cv2.CV_8U, ker) dist = cv2.blur(dist, (3, 3)).astype(np.float32) m = cv2.cvtColor(liquid_layer * dist, cv2.COLOR_GRAY2BGRA) m /= np.max(m, axis=(0, 1)) m *= c[4] # water is pale turqouise color = np.concatenate((175 / 255. * np.ones_like(m[..., :1]), 238 / 255. * np.ones_like(m[..., :1]), 238 / 255. * np.ones_like(m[..., :1])), axis=2) color = cv2.cvtColor(color, cv2.COLOR_BGR2BGRA) x = cv2.cvtColor(x, cv2.COLOR_BGR2BGRA) return cv2.cvtColor(np.clip(x + m * color, 0, 1), cv2.COLOR_BGRA2BGR) * 255 else: m = np.where(liquid_layer > c[3], 1, 0) m = gaussian(m.astype(np.float32), sigma=c[4]) m[m < 0.8] = 0 # m = np.abs(m) ** (1/c[4]) # mud brown color = np.concatenate((63 / 255. * np.ones_like(x[..., :1]), 42 / 255. * np.ones_like(x[..., :1]), 20 / 255. * np.ones_like(x[..., :1])), axis=2) color *= m[..., np.newaxis] x *= (1 - m[..., np.newaxis]) return np.clip(x + color, 0, 1) * 255
Example #24
Source File: make_imagenet_c_inception.py From robustness with Apache License 2.0 | 4 votes |
def spatter(x, severity=1): c = [(0.65,0.3,4,0.69,0.9,0), (0.65,0.3,3.5,0.68,0.9,0), (0.65,0.3,3,0.68,0.8,0), (0.65,0.3,1.2,0.65,1.8,1), (0.67,0.4,1.2,0.65,1.8,1)][severity - 1] x = np.array(x, dtype=np.float32) / 255. liquid_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1]) liquid_layer = gaussian(liquid_layer, sigma=c[2]) liquid_layer[liquid_layer < c[3]] = 0 if c[5] == 0: liquid_layer = (liquid_layer * 255).astype(np.uint8) dist = 255 - cv2.Canny(liquid_layer, 50, 150) dist = cv2.distanceTransform(dist, cv2.DIST_L2, 5) _, dist = cv2.threshold(dist, 20, 20, cv2.THRESH_TRUNC) dist = cv2.blur(dist, (3, 3)).astype(np.uint8) dist = cv2.equalizeHist(dist) # ker = np.array([[-1,-2,-3],[-2,0,0],[-3,0,1]], dtype=np.float32) # ker -= np.mean(ker) ker = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]]) dist = cv2.filter2D(dist, cv2.CV_8U, ker) dist = cv2.blur(dist, (3, 3)).astype(np.float32) m = cv2.cvtColor(liquid_layer * dist, cv2.COLOR_GRAY2BGRA) m /= np.max(m, axis=(0, 1)) m *= c[4] # water is pale turqouise color = np.concatenate((175 / 255. * np.ones_like(m[..., :1]), 238 / 255. * np.ones_like(m[..., :1]), 238 / 255. * np.ones_like(m[..., :1])), axis=2) color = cv2.cvtColor(color, cv2.COLOR_BGR2BGRA) x = cv2.cvtColor(x, cv2.COLOR_BGR2BGRA) return cv2.cvtColor(np.clip(x + m * color, 0, 1), cv2.COLOR_BGRA2BGR) * 255 else: m = np.where(liquid_layer > c[3], 1, 0) m = gaussian(m.astype(np.float32), sigma=c[4]) m[m < 0.8] = 0 # m = np.abs(m) ** (1/c[4]) # mud brown color = np.concatenate((63 / 255. * np.ones_like(x[..., :1]), 42 / 255. * np.ones_like(x[..., :1]), 20 / 255. * np.ones_like(x[..., :1])), axis=2) color *= m[..., np.newaxis] x *= (1 - m[..., np.newaxis]) return np.clip(x + color, 0, 1) * 255