Opencv+python realizes binarization of pictures (black and white pictures), and then realizes changing the specified color in the picture, which is classic and effective!
learning target:
When we use opencv to realize image processing, picture binarization and color replacement are two processing methods with relatively high frequency. As a calligraphy lover, I will take processing a pair of calligraphy pictures as an example to realize binarization and color replacement. Color Replacement:
Learning Content:
First prepare a picture that needs to be binarized:
we want to replace all the rice-character grids and the beige background with pure white for this exercise, so that we can get a beautiful and simple work. The binarization processing code is as follows:
import cv2 as cv
def load_image():
src=cv.imread('test.jpg')
h,w=src.shape[:2]
#src=cv.resize(src,(w*2,h*3))
return src
#全局阈值
def threshold_demo(image):
gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY)
#为0则使用自动寻找阈值的选项 使用自动寻找即用|分开。
#如下100为阈值,低于100的像素点全部置为255(即白色)
ret,binary=cv.threshold(gray,100,255,cv.THRESH_BINARY)#|cv.THRESH_TRIANGLE
print(ret)
cv.imshow('change',binary)
#保存二值化后图片change.jpg
cv.imwrite('change.jpg', binary, [int(cv.IMWRITE_JPEG_QUALITY), 70])
cv.waitKey(0)
cv.destroyAllWindows()
threshold_demo(load_image())
Processed picture:
Color Replacement:
Here we take replacing the color of the stamp as an example, let black be replaced by red:
first prepare a black and white picture:
color replacement code:
#准备好需要替换颜色的图片yinzhang.jpg
img_rgb = cv2.imread('yinzhang.jpg')
Conv_hsv_Gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
res, mask = cv2.threshold(Conv_hsv_Gray, 0, 255,cv2.THRESH_BINARY_INV |cv2.THRESH_OTSU)
#置换颜色[55, 67, 188]为需要置换的红色
#255为需要保留的颜色(即不被替换的颜色),利用掩膜思想覆盖黑色部分
img_rgb[mask == 255] = [55, 67, 188]
cv2.imshow("imgOriginal", img_rgb) # show windows
cv2.imwrite('change.jpg', img_rgb, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
cv2.imshow("output", res) # show windows
cv2.imshow("mask", mask) # show windows
cv2.waitKey(0)
Replacement result: