python使用opencv将Labelme生成的分割图转化成二值化分割图
https://blog.csdn.net/weixin_46716951/article/details/123657721
labelme分割图转为二值图:
import cv2 import os def convert_png2seg(input_dir,output_dir): files = os.listdir(input_dir) for file in files: part = file.split('.') part0 = part[0] part1 = part[1] img = cv2.imread(input_dir+file) img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) retval, binary = cv2.threshold(img_gray, 10, 255, cv2.THRESH_BINARY) #阈值处理 cv2.imwrite(output_dir + part0 + '.' + part1, binary) if __name__ == "__main__": input_dir = r"/home/cjk/下载/DeepLabV3Plus-Pytorch-master/output/" output_dir = r"/home/cjk/下载/DeepLabV3Plus-Pytorch-master/output_1/" convert_png2seg(input_dir,output_dir)
下边为原图以及产生的mask图
然后我们找一张想要替换的背景图
import cv2 person = cv2.imread("原图") back = cv2.imread("背景图") #这里将mask图转化为灰度图 mask = cv2.imread("mask图",cv2.IMREAD_GRAYSCALE) #将背景图resize到和原图一样的尺寸 back = cv2.resize(back,(person.shape[1],person.shape[0])) #这一步是将背景图中的人像部分抠出来,也就是人像部分的像素值为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 #这部分是将我们的人像抠出来,也就是背景部分的像素值为0 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("3.jpg",result)
下边为效果图