本文整理汇总了Python中cv2.distanceTransform方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.distanceTransform方法的具体用法?Python cv2.distanceTransform怎么用?Python cv2.distanceTransform使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2
的用法示例。
在下文中一共展示了cv2.distanceTransform方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: shadow_image
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例2: __call__
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例3: get_image
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例4: get_image
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例5: main
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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)
示例6: compute_dismap
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例7: uglify_image
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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')
示例8: calibrate_from_initialization
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例9: distance_transform
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例10: distance_transform
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例11: opencv_segmentation
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例12: distance_transform
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例13: ut_generate_grassland_mask
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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)
示例14: vis_uv
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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
示例15: spatter
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import distanceTransform [as 别名]
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