使用GAN(生成对抗网络)进行图像生成
def add_obj(background, img, x, y):
''''
将img融合到background上去
background: 背景
img: 要融合的裂缝图像
x,y: 要融合的位置
'''
bg = background.copy()
h_bg, w_bg = bg.shape[0], bg.shape[1]
h, w = img.shape[0], img.shape[1]
# Calculating coordinates of the top left corner of the object image to the background
x_tl = x - int(w/2)
y_tl = y - int(h/2)
# Calculating coordinates of the bottom right corner of the object image to the background
x_br = x + int(w/2)
y_br = y + int(h/2)
w1 = x_br - x_tl
h1 = y_br - y_tl
if (x_tl >= 0 and y_tl >= 0) and (x_br < w_bg and y_br < h_bg):
a = bg[y_tl:y_br, x_tl:x_br]
b = img[0:h1, 0:w1]
c = np.where(b>50, b, a)
bg[y_tl:y_br, x_tl:x_br] = c
bg[bg>50] = 255
bg[bg<=50] = 0
return bg, x_tl, y_tl, x_br, y_br
else:
return None
'''
生成黑白背景并随机生成噪声
'''
def add_small(w, h):
root_path = 'noise/small'
files_list = os.listdir(root_path)
n = len(files_list)
k = np.random.randint(0, n)
img = cv2.imread(os.path.join(root_path, files_list[k]), 0)
img = cv2.resize(img, (h, w))
return img
def add_big(w, h):
root_path = 'noise/big'
files_list = os.listdir(root_path)
n = len(files_list)
k = np.random.randint(0, n)
img = cv2.imread(os.path.join(root_path, files_list[k]), 0)
img = cv2.resize(img, (h, w))
return img
def get_xy(w, h, w1, h1):
a = w - w1 - 1
b = h - h1 - 1
x = np.random.randint(0, a)
y = np.random.randint(0, b)
return x, y
def add_noise(img):
w = img.shape[1]
h = img.shape[0]
# 小斑点
count = np.random.randint(100, 300)
for _ in range(0, count):
w1 = np.random.randint(10, 15)
h1 = np.random.randint(10, 15)
x, y = get_xy(w, h, w1, h1)
img[x:x+w1, y:y+h1] = add_small(w1, h1)
# 方形
count = np.random.randint(3, 5)
for _ in range(0, count):
w1 = np.random.randint(30, 50)
h1 = np.random.randint(30, 50)
x, y = get_xy(w, h, w1, h1)
img[x:x+w1, y:y+h1] = add_small(w1, h1)
# 长形
count = np.random.randint(3, 5)
for _ in range(0, count):
w1 = np.random.randint(10, 15)
h1 = np.random.randint(30, 50)
x, y = get_xy(w, h, w1, h1)
img[x:x+w1, y:y+h1] = add_small(w1, h1)
# 扁形
count = np.random.randint(3, 5)
for _ in range(0, count):
w1 = np.random.randint(30, 50)
h1 = np.random.randint(10, 15)
x, y = get_xy(w, h, w1, h1)
img[x:x+w1, y:y+h1] = add_small(w1, h1)
return img
阅读量:2017
点赞量:0
收藏量:0