1. 程式人生 > 實用技巧 >生成馬賽克圖片並且在對應的標籤中新增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)