本文整理匯總了Python中cv2.bilateralFilter方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.bilateralFilter方法的具體用法?Python cv2.bilateralFilter怎麽用?Python cv2.bilateralFilter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cv2
的用法示例。
在下文中一共展示了cv2.bilateralFilter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: face_smooth
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def face_smooth(self, im_bgr, smooth_rate=0.7, bi_ksize=15, sigma=100, ga_ksize=3):
"""Face smoothing.
Parameters
----------
im_bgr: mat
The Mat data format of reading from the original image using opencv.
smooth_rate: float, default is 0.7.
The face smoothing rate.
bi_ksize: int, default is 15.
The kernel size of bilateral filter.
sigma: int, default is 100.
The value of sigmaColor and sigmaSpace for bilateral filter.
ga_ksize: int, default is 3.
The kernel size of gaussian blur filter.
Returns
-------
type: mat
The result of face smoothing.
"""
im_bi = cv2.bilateralFilter(im_bgr, bi_ksize, sigma, sigma)
im_ga = cv2.GaussianBlur(im_bi, (ga_ksize, ga_ksize), 0, 0)
im_smooth = np.minimum(smooth_rate * im_ga + (1 - smooth_rate) * im_bgr, 255).astype('uint8')
return im_smooth
示例2: test_input_frame
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def test_input_frame(self):
"""Test if input frame preprocessed correctly. """
# setup
test_path = utils.get_full_path('docs/material_for_testing/face_and_hand.jpg')
test_image = cv2.imread(test_path)
# Because image loaded from local, and not received from web-cam, a flip is needed,
# inside frame_handler, a frame is supposed to be received from web-cam, hence it is flipped after receiving it.
test_image = cv2.flip(test_image, 1) # type: np.ndarray
expected = test_image.copy()
expected = cv2.bilateralFilter(expected, 5, 50, 100) # smoothing filter
expected = cv2.flip(expected, 1)
frame_handler = FrameHandler()
frame_handler.logger.setLevel(logging.DEBUG)
# run
# range [-1, 1] with a value of one being a “perfect match”.
frame_handler.input_frame = test_image
ssim = ImageTestTool.compare_imaged(frame_handler.input_frame, expected)
# print("SSIM: {}".format(ssim))
assert ssim >= 0.95
示例3: slicewise_bilateral_filter
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def slicewise_bilateral_filter(data_3d, d=3, sigmaColor=8, sigmaSpace=8):
img_batch_shape = data_3d.shape[:2] +(0,)
img_batch = np.empty(img_batch_shape, dtype='float32')
print (img_batch.shape)
print (data_3d.dtype)
try:
slices = data_3d.shape[2]
except Exception:
slices = 1
denoised_img = bilateralFilter(data_3d[:,:].astype('float32'),d, sigmaColor, sigmaSpace)
return denoised_img
for i in range(slices):
denoised_img = np.expand_dims(bilateralFilter(data_3d[:,:,i].astype('float32'),
d, sigmaColor, sigmaSpace), axis=2)
img_batch = np.concatenate((img_batch, denoised_img), axis=2)
return img_batch
開發者ID:mahendrakhened,項目名稱:Automated-Cardiac-Segmentation-and-Disease-Diagnosis,代碼行數:18,代碼來源:data_augmentation.py
示例4: avg_score
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def avg_score(test_dir, gt_dir, metric_name='ssim', smooth=False, sigma=75, verbose=False):
"""
Read images from two folders and calculate the average score.
"""
metric_name = metric_name.lower()
all_score = []
if metric_name == 'fsim':
matlab = matlab_wrapper.MatlabSession()
for name in sorted(sorted(os.listdir(gt_dir))):
test_img = Image.open(os.path.join(test_dir, name)).convert('L')
gt_img = Image.open(os.path.join(gt_dir, name)).convert('L')
if smooth:
test_img = cv.bilateralFilter(np.array(test_img),7,sigma,sigma)
if metric_name == 'ssim':
tmp_score = SSIM(gt_img, test_img)
elif metric_name == 'fsim':
tmp_score = FSIM(matlab, gt_img, test_img)
if verbose:
print('Image: {}, Metric: {}, Smooth: {}, Score: {}'.format(name, metric_name, smooth, tmp_score))
all_score.append(tmp_score)
return np.mean(np.array(all_score))
示例5: denoise
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def denoise(varr, method, **kwargs):
if method == 'gaussian':
func = cv2.GaussianBlur
elif method == 'anisotropic':
func = anisotropic_diffusion
elif method == 'median':
func = cv2.medianBlur
elif method == 'bilateral':
func = cv2.bilateralFilter
else:
raise NotImplementedError(
"denoise method {} not understood".format(method))
res = xr.apply_ufunc(
func,
varr,
input_core_dims=[['height', 'width']],
output_core_dims=[['height', 'width']],
vectorize=True,
dask='parallelized',
output_dtypes=[varr.dtype],
kwargs=kwargs)
return res.rename(varr.name + "_denoised")
示例6: cartoonise
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def cartoonise(self, img_rgb, num_down, num_bilateral, medianBlur, D, sigmaColor, sigmaSpace):
# 用高斯金字塔降低取樣
img_color = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)
for _ in range(num_down):
img_color = cv2.pyrDown(img_color)
# 重複使用小的雙邊濾波代替一個大的濾波
for _ in range(num_bilateral):
img_color = cv2.bilateralFilter(img_color, d=D, sigmaColor=sigmaColor, sigmaSpace=sigmaSpace)
# 升采樣圖片到原始大小
for _ in range(num_down):
img_color = cv2.pyrUp(img_color)
if not self.Save_Edge:
img_cartoon = img_color
else:
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
img_blur = cv2.medianBlur(img_gray, medianBlur)
img_edge = cv2.adaptiveThreshold(img_blur, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
blockSize=self.Adaptive_Threshold_Block_Size,
C=self.C)
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
img_edge = cv2.resize(img_edge, img_color.shape[:2][::-1])
img_cartoon = cv2.bitwise_and(img_color, img_edge)
return cv2.cvtColor(img_cartoon, cv2.COLOR_RGB2BGR)
示例7: _augment_images
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def _augment_images(self, images, random_state, parents, hooks):
result = images
nb_images = len(images)
seed = random_state.randint(0, 10**6)
samples_d = self.d.draw_samples((nb_images,), random_state=ia.new_random_state(seed))
samples_sigma_color = self.sigma_color.draw_samples((nb_images,), random_state=ia.new_random_state(seed+1))
samples_sigma_space = self.sigma_space.draw_samples((nb_images,), random_state=ia.new_random_state(seed+2))
for i in sm.xrange(nb_images):
ia.do_assert(images[i].shape[2] == 3, "BilateralBlur can currently only be applied to images with 3 channels.")
di = samples_d[i]
sigma_color_i = samples_sigma_color[i]
sigma_space_i = samples_sigma_space[i]
if di != 1:
result[i] = cv2.bilateralFilter(images[i], di, sigma_color_i, sigma_space_i)
return result
示例8: cartonize_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def cartonize_image(img, gray_mode=False):
"""Cartoonizes the image applying cv2.bilateralFilter()"""
# Get the sketch:
thresholded = sketch_image(img)
# Apply bilateral filter with "big numbers" to get the cartoonized effect:
filtered = cv2.bilateralFilter(img, 10, 250, 250)
# Perform 'bitwise and' with the thresholded img as mask in order to set these values to the output
cartoonized = cv2.bitwise_and(filtered, filtered, mask=thresholded)
if gray_mode:
return cv2.cvtColor(cartoonized, cv2.COLOR_BGR2GRAY)
return cartoonized
# Create the dimensions of the figure and set title:
示例9: cnvt_edged_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def cnvt_edged_image(img_arr, should_save=False):
# ratio = img_arr.shape[0] / 300.0
image = imutils.resize(img_arr,height=300)
gray_image = cv2.bilateralFilter(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY),11, 17, 17)
edged_image = cv2.Canny(gray_image, 30, 200)
if should_save:
cv2.imwrite('cntr_ocr.jpg')
return edged_image
示例10: PrepareImage
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def PrepareImage(image):
"""Converts color image to black and white"""
# work on gray scale
bw = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# remove noise, preserve edges
bw = cv2.bilateralFilter(bw, 9, 75, 75)
# binary threshold
bw = cv2.adaptiveThreshold(bw, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
return bw
示例11: preprocess_one_img
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def preprocess_one_img(img):
resize_img = _resize_image(img, 32) # 修改圖片的高度
# 對圖片進行濾波處理
resize_img = cv2.normalize(resize_img, dst=None, alpha=230, beta=20, norm_type=cv2.NORM_MINMAX)
resize_img = cv2.bilateralFilter(src=resize_img, d=3, sigmaColor=200, sigmaSpace=10)
resize_img = cv2.filter2D(resize_img, -1, kernel=np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32))
return resize_img
開發者ID:Mingtzge,項目名稱:2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement,代碼行數:9,代碼來源:preprocess_for_test.py
示例12: roiMask
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def roiMask(image, boundaries):
scale = max([1.0, np.average(np.array(image.shape)[0:2] / 400.0)])
shape = (int(round(image.shape[1] / scale)), int(round(image.shape[0] / scale)))
small_color = cv2.resize(image, shape, interpolation=cv2.INTER_LINEAR)
# reduce details and remove noise for better edge detection
small_color = cv2.bilateralFilter(small_color, 8, 64, 64)
small_color = cv2.pyrMeanShiftFiltering(small_color, 8, 64, maxLevel=1)
small = cv2.cvtColor(small_color, cv2.COLOR_BGR2HSV)
hue = small[::, ::, 0]
intensity = cv2.cvtColor(small_color, cv2.COLOR_BGR2GRAY)
edges = extractEdges(hue, intensity)
roi = roiFromEdges(edges)
weight_map = weightMap(hue, intensity, edges, roi)
_, final_mask = cv2.threshold(roi, 5, 255, cv2.THRESH_BINARY)
small = cv2.bitwise_and(small, small, mask=final_mask)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))
for (lower, upper) in boundaries:
lower = np.array([lower, 80, 50], dtype="uint8")
upper = np.array([upper, 255, 255], dtype="uint8")
# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(small, lower, upper)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
final_mask = cv2.bitwise_and(final_mask, mask)
# blur the mask for better contour extraction
final_mask = cv2.GaussianBlur(final_mask, (5, 5), 0)
return (final_mask, weight_map, scale)
示例13: upsample_single
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def upsample_single(a, size):
"""Upsample single image, with bilateral filtering.
Args:
a: [H', W', 3]
size: [W, H]
Returns:
b: [H, W, 3]
"""
interpolation = cv2.INTER_LINEAR
b = cv2.resize(a, size, interpolation=interpolation)
b = cv2.bilateralFilter(b, 5, 10, 10)
return b
示例14: upsample_single
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def upsample_single(self, a, size):
"""Upsample single image, with bilateral filtering.
Args:
a: [H', W', 3]
size: [W, H]
Returns:
b: [H, W, 3]
"""
interpolation = cv2.INTER_LINEAR
b = cv2.resize(a, size, interpolation=interpolation)
b = cv2.bilateralFilter(b, 5, 10, 10)
return b
示例15: ocr_test
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import bilateralFilter [as 別名]
def ocr_test(img, hsv_flag, avg_flag=False, gau_flag=False,
med_flag=False, bil_flag=False, inv_flag=True):
# Create a grayscale and HSV copy of the input image.
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# If the HSV flag is enabled, select white OR red -> (High S AND Mid H)'
if hsv_flag:
mask = cv2.inRange(img_hsv, (15, 50, 0), (160, 255, 255))
result_img = cv2.bitwise_and(img_gray, img_gray,
mask=cv2.bitwise_not(mask))
else:
result_img = img_gray
# Apply a post blurring filter according to the input flag given.
# https://docs.opencv.org/3.4.5/d4/d13/tutorial_py_filtering.html
if avg_flag:
result_img = cv2.blur(result_img, (5, 5))
elif gau_flag:
result_img = cv2.GaussianBlur(result_img, (5, 5), 0)
elif med_flag:
result_img = cv2.medianBlur(result_img, 5)
elif bil_flag:
result_img = cv2.bilateralFilter(result_img, 9, 75, 75)
# Invert the image to give the image a black on white background.
if inv_flag:
result_img = cv2.bitwise_not(result_img)
display_ocr_test_flags(hsv_flag, avg_flag, gau_flag,
med_flag, bil_flag, inv_flag)
show_ocr_result(result_img)
# Display the OCR test flags in a structured format.