可用于对于白底黑字的各种线性图标的全部整合成一个图,也可以进行透明化作为某个插图使用。
1.效果展示:
处理前:
处理后(蓝白底做背景):
处理前:
处理后(蓝白做背景):
2.函数解释
若是原图片不够清晰或者存在毛边,可以调用一下这两个函数
img_improve2(image, outpath) # 用于图片增强亮度和饱和度的
img_Brightness_contrast(img_array, outpath) # 用于增强图片对比度的
make_transparent(image_path, output_path) #用于实现图像透明处理的
import cv2
import numpy as np
from PIL import Image
def img_improve2(image, outpath):
b, g, r = cv2.split(image) # 拆
bH = cv2.equalizeHist(b) # 对三个通道图进行直方图均衡化
gH = cv2.equalizeHist(g)
rH = cv2.equalizeHist(r)
result = cv2.merge([bH, gH, rH]) # 合
res = np.hstack((image, result))
threshold = 20 # 设立一个阈值
h, w = image.shape[:2]
result[np.where((result[:,:,0] > threshold) & (result[:,:,1] > threshold) & (result[:,:,2] > threshold))] = [255, 255, 255] # 如果大于阈值就赋予白色,保证黑色留下
cv2.imencode('.png', result)[1].tofile(outpath)
return result
def img_Brightness_contrast(img_array, outpath):
img = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
bri_mean = np.mean(img)
Brightness = 2.0 # 对比度
contrast = 110 # 亮度.
img_a = Brightness * (img-bri_mean) + contrast + bri_mean
img_a = np.clip(img_a, 0, 255).astype(np.uint8)
cv2.imencode('.png', img_a)[1].tofile(outpath)
return img_a
def make_transparent(image_path, output_path):
image = Image.open(image_path)
if image.mode != 'RGBA':
image = image.convert('RGBA')
datas = image.getdata()
new_data = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
new_data.append((255, 255, 255, 0))
else:
new_data.append(item)
image.putdata(new_data)
image.save(output_path)
image_path = "C:/Users/Administrator/Desktop/111/黑白_7.jpg"
output_path = "C:/Users/Administrator/Desktop/111/transparent_1.png"
image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), 1)
# image = img_Brightness_contrast(image, "C:/Users/Administrator/Desktop/111/黑白_6.jpg")
# image = img_improve2(image, "C:/Users/Administrator/Desktop/111/黑白_7.jpg")
make_transparent(image_path, output_path)
标签:img,image,cv2,result,白底黑字,图像,path,透明化,255
From: https://blog.csdn.net/maxiubin666/article/details/137335264