python转换图片透明背景为白色
生活随笔
收集整理的這篇文章主要介紹了
python转换图片透明背景为白色
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
兩種方法,思路一致:
法一:
import cv2
# 修改透明背景為白色
def transparence2white(img):
sp=img.shape # 獲取圖片維度
width=sp[0] # 寬度
height=sp[1] # 高度
for yh in range(height):
for xw in range(width):
color_d=img[xw,yh] # 遍歷圖像每一個點,獲取到每個點4通道的顏色數據
if(color_d[3]==0): # 最后一個通道為透明度,如果其值為0,即圖像是透明
img[xw,yh]=[255,255,255,255] # 則將當前點的顏色設置為白色,且圖像設置為不透明
return img
img=cv2.imread('bar.png',-1) # 讀取圖片。-1將圖片透明度傳入,數據由RGB的3通道變成4通道
img=transparence2white(img) # 將圖片傳入,改變背景色后,返回
cv2.imwrite('bar.png',img) # 保存圖片,文件名自定義,也可以覆蓋原文件
法二:
from PIL import Image
def transparence2white(img):
# img=img.convert('RGBA') # 此步驟是將圖像轉為灰度(RGBA表示4x8位像素,帶透明度掩模的真彩色;CMYK為4x8位像素,分色等),可以省略
sp=img.size
width=sp[0]
height=sp[1]
print(sp)
for yh in range(height):
for xw in range(width):
dot=(xw,yh)
color_d=img.getpixel(dot) # 與cv2不同的是,這里需要用getpixel方法來獲取維度數據
if(color_d[3]==0):
color_d=(255,255,255,255)
img.putpixel(dot,color_d) # 賦值的方法是通過putpixel
return img
img=Image.open('bar.png')
img=transparence2white(img)
# img.show() # 顯示圖片
img.save('bar3.png') # 保存圖片
總結
以上是生活随笔為你收集整理的python转换图片透明背景为白色的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LPWAN
- 下一篇: 【算法】变邻域搜索算法(Variable