python將紅底證件照轉(zhuǎn)成藍(lán)底的實現(xiàn)方法
前言
emmm…9月1日開學(xué)季,手頭只有紅底證件照,但是學(xué)院要求要藍(lán)底,這可咋辦呢。懶得下ps了。自己擼起來吧。
方法一: lableme
lableme標(biāo)注完后。得到一個json文件,然后將這種json文件轉(zhuǎn)成掩碼圖.
# 代碼來自 https://blog.csdn.net/hello_dear_you/article/details/120130155
import json
import numpy as np
import cv2
# read json file
with open("origin_json/mypic.json", "r") as f:
data = f.read()
# convert str to json objs
data = json.loads(data)
# get the points
points = data["shapes"][0]["points"]
points = np.array(points, dtype=np.int32) # tips: points location must be int32
# read image to get shape
image = cv2.imread("origin_png/person.jpg")
# create a blank image
mask = np.zeros_like(image, dtype=np.uint8)
# fill the contour with 255
cv2.fillPoly(mask, [points], (255, 255, 255))
# save the mask
cv2.imwrite("mask/person_mask.png", mask)
大概是這樣:

然后利用這個mask生成圖片
# 參考自: https://www.jianshu.com/p/1961aa0c02ee
import cv2
import numpy as np
origin_png = 'origin_png/person.jpg'
# maskPath = 'mask/person_mask.png'
maskPath = 'mask/bmv2.png'
result_png = 'result_png/result_png.png'
maskImg = cv2.imread(maskPath)
img = cv2.imread(origin_png)
assert maskImg.shape == img.shape, 'maskImg.shape != origin_png.shape'
h, w = img.shape[0], img.shape[1]
print('圖片寬度: {}, 高度: {}'.format(h, w))
rgb = (19,122,171)
bgr = (rgb[2], rgb[1], rgb[0])
# (B, G, R)
for i in range(h):
for j in range(w):
if (maskImg[i, j] == 0).all():
img[i, j] = bgr
cv2.imwrite(result_png, img)
print('圖片寫入 {} 成功'.format(result_png))由于人長得一般,就不放圖了…
缺點:
lableme標(biāo)注時挺費力,并且難以避免人與背景邊緣會有殘留紅色像素的情況。

方法二: 閾值
該方法通過比較像素的RGB與背景的RGB來區(qū)分是否為圖像背景。
Opencv
import cv2
import numpy as np
def mean_square_loss(a_np, b_np):
sl = np.square(a_np - b_np)
return np.mean(sl)
def change_red2blue(origin_png, result_png):
img = cv2.imread(origin_png)
h, w = img.shape[0], img.shape[1]
print('圖片寬度: {}, 高度: {}'.format(h, w))
origin_rgb = (168,36,32) # 可以用瀏覽器啥的控制臺工具提取出背景的rgb值
origin_bgr = (origin_rgb[2], origin_rgb[1], origin_rgb[0])
target_rgb = (19,122,171) # 藍(lán)底RBG
target_bgr = (target_rgb[2], target_rgb[1], target_rgb[0])
for i in range(h):
for j in range(w):
# (B, G, R)
if mean_square_loss(img[i, j], origin_bgr) < 50:
img[i, j] = target_bgr
cv2.imwrite(result_png, img)
print('圖片寫入 {} 成功'.format(result_png))
if __name__ == '__main__':
# origin_png = 'result_png/result_png.png'
origin_png = 'origin_png/person.jpg'
result_png = 'result_png/result_refine.png'
change_red2blue(origin_png, result_png)結(jié)果人與背景邊緣仍會存在紅色像素殘留

PIL
from torchvision.transforms.functional import to_tensor, to_pil_image
from PIL import Image
import torch
import time
def mean_square_loss(a_ts, b_ts):
# print(a_ts.shape)
# print(b_ts)
sl = (a_ts - b_ts) ** 2
return sl.sum()
def change_red2blue(origin_png, result_png):
src = Image.open(origin_png)
src = to_tensor(src)
# print(src.shape) # torch.Size([3, 800, 600])
# channel: (R, G, B) / 255
h, w = src.shape[1], src.shape[2]
pha = torch.ones(h, w, 3)
bg = torch.tensor([168,36,32]) / 255
target_bg = torch.tensor([19,122,171]) / 255
# C, H, W -> H, W, C
src = src.permute(1, 2, 0)
for i in range(h):
for j in range(w):
if mean_square_loss(src[i][j], bg) < 0.025: # 0.025是閾值,超參數(shù)
pha[i][j] = torch.tensor([0.0, 0.0, 0.0])
# H, W, C -> C, H, W
src = src.permute(2, 0, 1)
pha = pha.permute(2, 0, 1)
com = pha * src + (1 - pha) * target_bg.view(3, 1, 1)
to_pil_image(com).save(result_png)
if __name__ == '__main__':
origin_png = 'origin_png/person.jpg'
result_png = 'result_png/com.png'
start_time = time.time()
change_red2blue(origin_png, result_png)
spend_time = round(time.time() - start_time, 2)
print('生成成功,共花了 {} 秒'.format(spend_time))
該方法質(zhì)量較好,但一張圖片大概需要12秒。

方法三: Background MattingV2
Real-Time High-Resolution Background Matting
CVPR 2021 oral
論文:https://arxiv.org/abs/2012.07810
代碼:https://github.com/PeterL1n/BackgroundMattingV2
github的readme.md有inference的colab鏈接,可以用那個跑
由于這篇論文是需要輸入一張圖片(例如有人存在的草地上)和背景圖片的(如果草地啥的), 然后模型會把人摳出來。
于是這里我需要生成一個背景圖片。
首先我先借助firefox的顏色拾取器(或者微信截圖,或者一些在線工具,例如菜鳥工具),得到十六進制,再用在線轉(zhuǎn)換工具轉(zhuǎn)成rgb。
然后生成一個背景圖片。
import cv2
import numpy as np
image = cv2.imread("origin_png/person.jpg")
origin_rgb = (168,36,32) # 可以用瀏覽器啥的控制臺工具提取出背景的rgb值
origin_bgr = (origin_rgb[2], origin_rgb[1], origin_rgb[0])
image[:, :] = origin_bgr
cv2.imwrite("mask/bg.png", image)
需要上傳人的照片和背景照片, 如果名字和路徑不一樣則需要修改一下代碼
src = Image.open('src.png')
bgr = Image.open('bgr.png')另外原論文是邊綠底,要變藍(lán)底,白底,紅底則可以修改RGB值,舉個例子,原來是這樣的(綠底, RGB120, 255, 155)
com = pha * fgr + (1 - pha) * torch.tensor([120/255, 255/255, 155/255], device='cuda').view(1, 3, 1, 1)
那么加入我要換白底(255, 255, 255),就是
com = pha * fgr + (1 - pha) * torch.tensor([255/255, 255/255, 255/255], device='cuda').view(1, 3, 1, 1)
假如像我換藍(lán)底(19,122,171)具體深淺可以調(diào)節(jié)一下RGB,就是
com = pha * fgr + (1 - pha) * torch.tensor([19/255, 122/255, 171/255], device='cuda').view(1, 3, 1, 1)
總結(jié): 其實這種方法從 任何顏色的照片 都可以 換成任何顏色的底。只要換下RGB.
然后就輸出圖片了??梢钥吹叫Ч喈?dāng)好。不愧是oral。

原論文可以實現(xiàn)發(fā)絲級效果

報錯解決方案
can’t divided by 4 / can’t divided by 16
由于該骨干模型可能進行4倍或16倍下采樣,因此如果您的證件照不是該倍數(shù)的話,有兩種選擇方案。一種是padding, 填充后再送入模型,然后出結(jié)果后再用clip函數(shù)裁剪。另一種方式是resize, 給resize到規(guī)定倍數(shù)的寬和高。
這兩種方案需要的代碼都可以從這篇博文找到: python圖像填充與裁剪/resize
到此這篇關(guān)于python將紅底證件照轉(zhuǎn)成藍(lán)底的文章就介紹到這了,更多相關(guān)python證件照轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Prometheus開發(fā)中間件Exporter過程詳解
這篇文章主要介紹了Prometheus開發(fā)中間件Exporter過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11
詳解python編程slice與indices函數(shù)用法示例
這篇文章主要介紹了詳解python編程中slice與indices使用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2021-09-09
Python使用Beautiful?Soup(BS4)庫解析HTML和XML
這篇文章介紹了Python使用Beautiful?Soup(BS4)庫解析HTML和XML的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
解決安裝pycharm后不能執(zhí)行python腳本的問題
今天小編就為大家分享一篇解決安裝pycharm后不能執(zhí)行python腳本的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
python把數(shù)組中的數(shù)字每行打印3個并保存在文檔中的方法
今天小編就為大家分享一篇python把數(shù)組中的數(shù)字每行打印3個并保存在文檔中的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Python 編碼處理-str與Unicode的區(qū)別
本文主要介紹Python 編碼處理的問題,這里整理了相關(guān)資料,并詳細(xì)說明如何處理編碼問題,有需要的小伙伴可以參考下2016-09-09

