其他分享
首页 > 其他分享> > 生成马赛克图片并且在对应的标签中添加mask区域,用于二值图训练

生成马赛克图片并且在对应的标签中添加mask区域,用于二值图训练

作者:互联网

 1 import cv2
 2 import os
 3 import numpy as np
 4 # 只需要调整neighbor 越大马赛克的单位块越大
 5 def do_mosaic(frame, x, y, w, h, neighbor=12):
 6     """
 7     马赛克的实现原理是把图像上某个像素点一定范围邻域内的所有点用邻域内左上像素点的颜色代替,这样可以模糊细节,但是可以保留大体的轮廓。
 8     :param frame: opencv frame
 9     :param int x :  马赛克左顶点
10     :param int y:  马赛克右顶点
11     :param int w:  马赛克宽
12     :param int h:  马赛克高
13     :param int neighbor:  马赛克每一块的宽
14     """
15     fh, fw = frame.shape[0], frame.shape[1]
16     if (y + h > fh) or (x + w > fw):
17         print()
18         return
19     for i in range(0, h - neighbor, neighbor):  # 关键点0 减去neightbour 防止溢出
20         for j in range(0, w - neighbor, neighbor):
21             rect = [j + x, i + y, neighbor, neighbor]
22             color = frame[i + y][j + x].tolist()  # 关键点1 tolist
23             left_up = (rect[0], rect[1])
24             right_down = (rect[0] + neighbor - 1, rect[1] + neighbor - 1)  # 关键点2 减去一个像素
25             cv2.rectangle(frame, left_up, right_down, color, -1)
26     return frame
27 
28 # 原图路径
29 oriRoot = r"D:\jianfeng\ali\generateMask\pic"
30 # mask路径
31 maskRoot = r"D:\jianfeng\ali\generateMask\mask"
32 pics = os.listdir(oriRoot)
33 for pic in pics:
34     # im = cv2.imread("81.jpg", 1)
35     im = cv2.imread(os.path.join(oriRoot, pic), 1)
36 
37     print(os.path.join(oriRoot, pic))
38     print(im)
39     imMask = cv2.imread(os.path.join(maskRoot, pic.split(".")[0]+".png"), 1)
40     hPic = im.shape[0]
41     wPic = im.shape[0]
42     x = np.random.randint(20, hPic-500)
43     y = np.random.randint(20, wPic-500)
44     w = np.random.randint(20, 400)
45     h = np.random.randint(20, 400)
46     imnew = do_mosaic(im, x, y, w, h)
47     print(imnew)
48     imMask[y:y+h, x:x+w] = 255
49 
50     # show
51     cv2.imshow('mosaic', cv2.resize(imnew, (500, 500)))
52     cv2.imshow('mosaicMask', cv2.resize(imMask, (500, 500)))
53     cv2.waitKey(0)

 

标签:mask,frame,cv2,param,马赛克,neighbor,二值,500
来源: https://www.cnblogs.com/bob-jianfeng/p/14007343.html