The realization principle of sketch
To achieve an image processing effect, we first need to grasp the specific principle of its implementation.
Believe often use PS user affirmation oneself through this software processing sketch effect realization. So, we can refer to the steps of the same PHOTOSHOP sketch effect:
- Color removal: because the sketch has only two colors, black and white, so the color image must be converted to gray image
- Duplicate the layer and invert the color. The inverse color formula is: Y(I,j)= 255-x (I,j)
- Gaussian blur is performed on the reflected image
- Select the color dodge effect for the blurred image overlay mode
The formula for color dodge is as follows:
C=MIN (A+ (A+B)/(255-b), 255)
C: Mixed results
A: Pixels after the color is removed
B: Pixels after gaussian blur
Inverse color implementation
Since the step has the operation of invert color, then how to implement the operation of invert color in OpenCV?
In fact, the invert color can be implemented by the cv2.addweighted () function. The principle is to overlay an image with a zero pixel image and a grayscale image. The zero pixel image must have the same width and height as the original image, and its gamma parameter must be set to 255.
The specific code is as follows:
def sketch_effect(img) :
new_img = img.copy()
h, w, n = img.shape
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
zero_img = np.zeros((h, w), dtype=np.uint8)
gray = cv2.addWeighted(gray, -1, zero_img, 0.255.0)
Copy the code
The inverse color operation can be converted into the following mathematical formula:
dst=src1alpha+src2beta+gamma
Gaussian filter
Through the above code, we achieved the first step to convert to grayscale image, but also to achieve the second step to reverse color operation.
Next, what we need to do is implement the high pass filter. High pass filtering has been introduced in 17 blog posts on image smoothing. The high-pass filtering function is cv2.gaussianblur ().
Next, let’s do the third operation on the image: the invert color image for high pass filtering. The code is as follows:
def sketch_effect(img) :
h, w, n = img.shape
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
zero_img = np.zeros((h, w), dtype=np.uint8)
anti_color = cv2.addWeighted(gray, -1, zero_img, 0.255.0)
cv2.imshow("2", anti_color)
grayGB = cv2.GaussianBlur(anti_color, (15.15), 0)
new_img = cv2.addWeighted(gray, 0.5, grayGB, 0.5.0)
return new_img
if __name__ == "__main__":
img = cv2.imread("4.jpg")
cv2.imshow("0", img)
cv2.imshow("1", sketch_effect(img))
cv2.waitKey()
cv2.destroyAllWindows()
Copy the code
After running, the effect is as follows:
0 on the left is the original image, 1 in the middle is the sketch effect, and 2 on the right is the inverted color image.