1.生成分割后的mask
原图和mask如下:
2.mask二值化
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
def getimg():
return Image.open("2.png")
def showimg(img, isgray=False):
plt.axis("off")
if isgray == True:
plt.imshow(img, cmap='gray')
else:
plt.imshow(img)
plt.show()
im5 = getimg()
im5 = np.array(im5.convert('L'))
im5 = np.where(im5[...,:] < 165, 0, 255)
showimg(Image.fromarray(im5), True)
生成如图:
3. mask二值化后取反
import os
from PIL import Image
import numpy as np
def resize(imgPath, savePath):
files = os.listdir(imgPath)
files.sort()
print('****************')
print('input :', imgPath)
print('start...')
for file in files:
fileType = os.path.splitext(file)
if fileType[1] == '.png':
new_png = Image.open(imgPath + '/' + file)
matrix = 255 - np.asarray(new_png)
new_png = Image.fromarray(matrix)
new_png.save(savePath + '/' + file)
print('down!')
print('****************')
if __name__ == '__main__':
dataPath = 'G:\\666\\2\\'
savePath = 'G:\\666\\2\\'
resize(dataPath, savePath)
如图:
4.把mask分割后的图像提取出来
import os
import cv2
import numpy as np
im1_path = 'G:/666/1/'
im2_path = 'G:/666/2/'
num = len(os.listdir(im1_path))
for i in range(num):
img1 = cv2.imread(os.path.join(im1_path, os.listdir(im1_path)[i]))
img2 = cv2.imread(os.path.join(im2_path,os.listdir(im2_path)[i]), cv2.IMREAD_GRAYSCALE)
h,w,c = img1.shape
img3 = np.zeros((h,w,4))
img3[:,:,0:3] = img1
img3[:,:,3] = img2
cv2.imwrite('G:/666/3/' + '%s.png' % os.listdir(im1_path)[i], img3)
生成图像: 另一种出来版本是黑色背景:
import cv2
person = cv2.imread("1.png")
mask = cv2.imread("6.png",cv2.IMREAD_GRAYSCALE)
mask = mask / 255.0
person[:,:,0] = person[:,:,0] * mask
person[:,:,1] = person[:,:,1] * mask
person[:,:,2] = person[:,:,2] * mask
cv2.imwrite("3.jpg", person)
出图如下: 如果加上背景的话:(像素黑的就是0,随便附加颜色)
import cv2
person = cv2.imread("1.png")
back = cv2.imread("0.png")
mask = cv2.imread("6.png",cv2.IMREAD_GRAYSCALE)
back = cv2.resize(back,(person.shape[1],person.shape[0]))
scenic_mask =~mask
scenic_mask = scenic_mask / 255.0
back[:,:,0] = back[:,:,0] * scenic_mask
back[:,:,1] = back[:,:,1] * scenic_mask
back[:,:,2] = back[:,:,2] * scenic_mask
mask = mask / 255.0
person[:,:,0] = person[:,:,0] * mask
person[:,:,1] = person[:,:,1] * mask
person[:,:,2] = person[:,:,2] * mask
result = cv2.add(back,person)
cv2.imwrite("88.jpg", result)
5.把mask分割后的图像可视化出来同步
from PIL import Image
import matplotlib.pyplot as plt
image1 = Image.open("1.png")
image2 = Image.open("6.png")
image1 = image1.convert('RGBA')
image2 = image2.convert('RGBA')
image = Image.blend(image1, image2, 0.3)
image.save("test1.png")
image.show()
|