import cv2 as cv
import PIL.Image as Image
import numpy as np
def threshold_demo(image): #全局阈值
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY|cv.THRESH_OTSU)
return binary
#以第一个像素为准,相同色改为透明
def transparent_back(img):
img = img.convert('RGBA')
L, H = img.size
color_0 = img.getpixel((0,0))
for h in range(H):
for l in range(L):
dot = (l,h)
color_1 = img.getpixel(dot)
if color_1 == color_0:
color_1 = color_1[:-1] + (0,)
img.putpixel(dot,color_1)
return img
if __name__ == '__main__':
src = cv.imread('C:/Users/Administrator/Desktop/sig.jpg')
binary = threshold_demo(src)
cv.imwrite('C:/Users/Administrator/Desktop/binary.png',binary)
img=Image.open('C:/Users/Administrator/Desktop/binary.png')
img=transparent_back(img)
img.save('C:/Users/Administrator/Desktop/signature.png')