说明
这个程序将图片二值化以后,将白色的部分转成透明。
程序使用了python3 和 opencv.
通过pip3安装opencv库
Bash
pip3 install opencv-python
主程序代码
Python
#!/bin/python
import sys
import cv2 as cv
import numpy as np
if len(sys.argv) < 3:
print("python pic_trans.py [文件名] [不带后缀的生成后文件名]")
exit()
image=cv.imread(sys.argv[1])
image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, image = cv.threshold(image, 0, 255, cv.THRESH_BINARY|cv.THRESH_OTSU)
image = cv.cvtColor(image, cv.COLOR_GRAY2RGB)
b, g, r = cv.split(image)
alpha_channel = np.ones(b.shape, dtype=b.dtype) * 255
alpha_channel[:, :int(b.shape[0])] = 10
image = cv.merge([b, g, r, alpha_channel])
height,width,channel = image.shape
for x in range(0,width):
for y in range(0,height):
if image[y][x][0] == 255:
image[y][x][3] = 0
else:
image[y][x][3] = 255
cv.imwrite("%s.png" % sys.argv[2],image)