import cv2
import numpy as np
def empty_function(*arg):
pass
def SmootherEdgesTrackbar(img, win_name):
trackbar_name = win_name + "Trackbar"
cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)
cv2.resizeWindow(win_name, 1000, 500)
cv2.createTrackbar("first_blur", win_name, 3, 255, empty_function)
cv2.createTrackbar("second_blur", win_name, 3, 255, empty_function)
cv2.createTrackbar("threshold", win_name, 0, 255, empty_function)
while True:
first_blur_pos = cv2.getTrackbarPos("first_blur", win_name)
second_blur_pos = cv2.getTrackbarPos("second_blur", win_name)
thresh_pos = cv2.getTrackbarPos("threshold", win_name)
if first_blur_pos < 3:
first_blur_pos = 3
if second_blur_pos < 3:
second_blur_pos = 3
img_res = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_res = smoother_edges(img_res, (first_blur_pos * 2 + 1, first_blur_pos * 2 + 1),
(second_blur_pos * 2 + 1, second_blur_pos * 2 + 1))
_, img_res = cv2.threshold(img_res, thresh_pos, 255, 0)
cv2.imshow(win_name, img_res)
key = cv2.waitKey(1) & 0xFF
if key == ord("c"):
break
cv2.destroyAllWindows()
return img_res
def unsharp_mask(img, blur_size, imgWeight, gaussianWeight):
gaussian = cv2.GaussianBlur(img, blur_size, 0)
return cv2.addWeighted(img, imgWeight, gaussian, gaussianWeight, 0)
def smoother_edges(img, first_blur_size, second_blur_size=(5, 5),
imgWeight=1.5, gaussianWeight=-0.5):
# blur the image before unsharp masking
img = cv2.GaussianBlur(img, first_blur_size, 0)
# perform unsharp masking
return unsharp_mask(img, second_blur_size, imgWeight, gaussianWeight)
# read the image
img = cv2.imread("sample.jpg")
# smoothen edges
img = SmootherEdgesTrackbar(img, "Smoother Edges Trackbar")
# show and save image
cv2.imshow("img", img)
cv2.imwrite("result.png", img)
cv2.waitKey(0)
编辑: 当您确定适合您的值后,只需删除滑块功能,并使用固定值执行步骤。 算法如下:
convert to gray
blur
unsharp mask
threshold
在 smoother_edges() 函数中,将 2 个中间步骤合并。