对图片处理,亮度、翻转、水印、噪声、图中图
# coding: utf-8
import cv2
import numpy as np
import random
import os
import logging
import time
# from concurrent.futures import ThreadPoolExecutor, as_completed
logging.basicConfig(
filename='conver_image.log',
format='[%(asctime)s][%(threadName)s:%(thread)d][%(filename)s:%(lineno)d]' \
'[%(levelname)s]: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO
)
slog = logging.getLogger("conver_image")
save_path = "./ty_images"
debug = False
def save_image(img, path, name):
try:
if not os.path.exists(path):
os.makedirs(path)
except Exception as e:
slog.error("save_image\t{}\t{}\t{}".format(path, name, e))
cv2.imwrite(os.path.join(path, name), img)
# cv2.imwrite("./tr/{}".format() , img)
def contrast_brightness(img, c, b):
# 亮度就是每个像素所有通道都加上b
blank = np.zeros(img.shape, img.dtype) # np.zeros(img.shape, dtype=uint8)
# cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]])
# dst = src1 * alpha + src2 * beta + gamma;
dst = cv2.addWeighted(img, c, blank, 1 - c, b)
return dst
def mark_image(img, x1, y1, x2, y2, dis):
new_image = img[x1:x2, y1:y2]
new_image_mark = new_image[::dis, ::dis]
dst = img.copy()
nx, ny = new_image_mark.shape[:2]
for i in range(nx):
for j in range(ny):
dst[x1 + i * dis:x1 + (i + 1) * dis, y1 + j * dis:y1 + (j + 1) * dis] = new_image_mark[i, j]
return dst
def add_watermark(img, logo_mark, c):
logo_w, logo_h = logo_mark.shape[:2]
new_logo = ""
if logo_w >= img.shape[0] or logo_h >= img.shape[1]:
fx = min(img.shape[0] * 0.9 / logo_w, img.shape[1] * 0.9 / logo_h)
new_logo = cv2.resize(logo_mark, (0, 0), fx=fx, fy=fx, interpolation=cv2.INTER_AREA)
logo_w, logo_h = new_logo.shape[:2]
dst = img.copy()
left = random.randint(0, img.shape[0] - logo_w - 1)
top = random.randint(0, img.shape[1] - logo_h - 1)
# cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]])
# dst = src1 * alpha + src2 * beta + gamma;
if new_logo != "":
dst[left:left + logo_w, top:top + logo_h] = cv2.addWeighted(
img[left:left + logo_w, top:top + logo_h], c, new_logo, 1 - c, 0
)
else:
dst[left:left + logo_w, top:top + logo_h] = cv2.addWeighted(
img[left:left + logo_w, top:top + logo_h], c, logo_mark, 1 - c, 0
)
return dst
def scale_flip(img, fx, flip):
dst = cv2.resize(img, (0, 0), fx=fx, fy=fx, interpolation=cv2.INTER_AREA)
# dst = cv2.flip(img, 0) # 上下翻转
# dst = cv2.flip(img, 1) # 左右翻转
dst = cv2.flip(dst, flip)
return dst
def add_noise(img, type, percetage):
def clamp(pv):
if pv > 255:
return 255
if pv < 0:
return 0
else:
return pv
# 定义添加椒盐噪声的函数
def SaltAndPepper(src, percetage):
NoiseImg = src.copy()
NoiseNum = int(percetage * src.shape[0] * src.shape[1])
for i in range(NoiseNum):
randX = random.randint(2, src.shape[0] - 3)
randY = random.randint(2, src.shape[1] - 3)
if random.randint(0, 1) == 0:
NoiseImg[randX - 1:randX + 1, randY - 1:randY + 1] = 0
else:
NoiseImg[randX - 1:randX + 1, randY - 1:randY + 1] = 255
return NoiseImg
def GaussianNoise(src, means, sigma, percetage):
NoiseImg = src.copy()
NoiseNum = int(percetage * src.shape[0] * src.shape[1])
for i in range(NoiseNum):
randX = random.randint(2, src.shape[0] - 3)
randY = random.randint(2, src.shape[1] - 3)
NoiseImg[randX - 1:randX + 1, randY - 1:randY + 1, 0] = clamp(
NoiseImg[randX, randY, 0] + random.gauss(means, sigma))
NoiseImg[randX - 1:randX + 1, randY - 1:randY + 1, 1] = clamp(
NoiseImg[randX, randY, 1] + random.gauss(means, sigma))
NoiseImg[randX - 1:randX + 1, randY - 1:randY + 1, 2] = clamp(
NoiseImg[randX, randY, 2] + random.gauss(means, sigma))
return NoiseImg
if type == 0:
return SaltAndPepper(img, percetage)
elif type == 1:
return GaussianNoise(img, 100, 60, percetage)
else:
raise Exception("no know type")
def image_in_image(img, background, fx):
fx = background.shape[0] * fx / img.shape[0]
fx = min(fx, background.shape[1] * fx / img.shape[1])
fx = min(fx, background.shape[1] / img.shape[1] - 0.01, background.shape[0] / img.shape[0] - 0.01)
fx = max(fx, 0.08)
dst = cv2.resize(img, (0, 0), fx=fx, fy=fx, interpolation=cv2.INTER_AREA)
dst_w, dst_h = dst.shape[:2]
left = random.randint(0, background.shape[0] - dst_w - 1)
top = random.randint(0, background.shape[1] - dst_h - 1)
# cv2.addWeighted(src1, alpha, src2, beta, gamma[, dst[, dtype]])
# dst = src1 * alpha + src2 * beta + gamma;
background[left:left + dst_w, top:top + dst_h] = cv2.addWeighted(
background[left:left + dst_w, top:top + dst_h], 0, dst, 1, 0
)
return background
def gen_images_1(img, name, suffix, type_path="contrast_brightness"):
brights_list = [
[0.5, 0], [0.5, 50],
[0.7, 0], [0.7, 50],
[1.0, 0], [1.0, 50],
[1.3, 0], [1.3, -50],
[1.5, 0], [1.5, -50],
]
if debug:
tmp = img
for i, one in enumerate(brights_list):
try:
dst = contrast_brightness(img, one[0], one[1])
save_image(
dst,
os.path.join(save_path, type_path, str(i)),
"{}_{}_{}.{}".format(name, type_path, i, suffix)
)
slog.info("{}\t{}.{} {} save_ok".format(type_path, name, suffix, i))
if debug:
tmp = np.hstack((tmp, dst))
except Exception as e:
slog.error("{}\t{}.{}\t{}\t{}".format(type_path, name, suffix, i, e))
if debug:
cv2.imshow("con_bri_demo", tmp)
cv2.waitKey(0)
cv2.destroyAllWindows()
def gen_images_2(img, name, suffix, type_path="mosaic"):
mark_list = [
[0.2, 0.1, 0.6, 0.5, 5],
[0.2, 0.2, 0.5, 0.4, 10],
[0.3, 0.4, 0.8, 0.7, 15],
[0.4, 0.3, 0.9, 0.5, 20],
[0.1, 0.2, 0.5, 0.6, 25],
[0.6, 0.4, 0.9, 0.5, 30],
[0.2, 0.2, 0.6, 0.6, 35],
[0.0, 0.3, 0.6, 0.5, 40],
[0.3, 0.2, 0.9, 0.6, 45],
[0.2, 0.1, 0.8, 0.5, 50],
]
if debug:
tmp = img
for i, one in enumerate(mark_list):
try:
one[0] = int(one[0] * img.shape[0])
one[1] = int(one[1] * img.shape[1])
one[2] = int(one[2] * img.shape[0])
one[3] = int(one[3] * img.shape[1])
dst = mark_image(img, one[0], one[1], one[2], one[3], one[4])
save_image(
dst,
os.path.join(save_path, type_path, str(i)),
"{}_{}_{}.{}".format(name, type_path, i, suffix)
)
slog.info("{}\t{}.{} {} save_ok".format(type_path, name, suffix, i))
if debug:
tmp = np.hstack((tmp, dst))
except Exception as e:
slog.error("{}\t{}.{}\t{}\t{}".format(type_path, name, suffix, i, e))
if debug:
cv2.imshow("con_bri_demo", tmp)
cv2.waitKey(0)
cv2.destroyAllWindows()
def gen_image_3(img, name, suffix, type_path="watermark"):
operator_list = [
[cv2.imread("./data/1.png", cv2.IMREAD_COLOR), 0.0],
[cv2.imread("./data/1.png", cv2.IMREAD_COLOR), 0.5],
[cv2.imread("./data/2.png", cv2.IMREAD_COLOR), 0.1],
[cv2.imread("./data/2.png", cv2.IMREAD_COLOR), 0.6],
[cv2.imread("./data/3.png", cv2.IMREAD_COLOR), 0.2],
[cv2.imread("./data/3.png", cv2.IMREAD_COLOR), 0.7],
[cv2.imread("./data/4.png", cv2.IMREAD_COLOR), 0.3],
[cv2.imread("./data/4.png", cv2.IMREAD_COLOR), 0.8],
[cv2.imread("./data/5.png", cv2.IMREAD_COLOR), 0.4],
[cv2.imread("./data/5.png", cv2.IMREAD_COLOR), 0.9],
]
if debug:
tmp = img
for i, one in enumerate(operator_list):
try:
dst = add_watermark(img, one[0], one[1])
save_image(
dst,
os.path.join(save_path, type_path, str(i)),
"{}_{}_{}.{}".format(name, type_path, i, suffix)
)
slog.info("{}\t{}.{} {} save_ok".format(type_path, name, suffix, i))
if debug:
tmp = np.hstack((tmp, dst))
except Exception as e:
slog.error("{}\t{}.{}\t{}\t{}".format(type_path, name, suffix, i, e))
if debug:
cv2.imshow("con_bri_demo", tmp)
cv2.waitKey(0)
cv2.destroyAllWindows()
def gen_image_4(img, name, suffix, type_path="scale_flip"):
operator_list = [
[0.5, 0], [0.5, 1],
[0.6, 0], [0.6, 1],
[0.7, 0], [0.7, 1],
[0.8, 0], [0.8, 1],
[0.9, 0], [0.9, 1],
]
if debug:
tmp = img
for i, one in enumerate(operator_list):
try:
dst = scale_flip(img, one[0], one[1])
save_image(
dst,
os.path.join(save_path, type_path, str(i)),
"{}_{}_{}.{}".format(name, type_path, i, suffix)
)
slog.info("{}\t{}.{} {} save_ok".format(type_path, name, suffix, i))
if debug:
tmp = np.hstack((tmp,
cv2.copyMakeBorder(
dst,
0, img.shape[1] - dst.shape[1], 0, img.shape[0] - dst.shape[0],
cv2.BORDER_CONSTANT,
value=[255, 255, 255]
)))
except Exception as e:
slog.error("{}\t{}.{}\t{}\t{}".format(type_path, name, suffix, i, e))
if debug:
cv2.imshow("con_bri_demo", tmp)
cv2.waitKey(0)
cv2.destroyAllWindows()
def gen_image_5(img, name, suffix, type_path="noise"):
operator_list = [
[0.0005, 0], [0.0004, 1],
[0.001, 0], [0.0009, 1],
[0.004, 0], [0.0015, 1],
[0.01, 0], [0.002, 1],
[0.04, 0], [0.009, 1],
]
if debug:
tmp = img
for i, one in enumerate(operator_list):
try:
dst = add_noise(img, one[1], one[0])
save_image(
dst,
os.path.join(save_path, type_path, str(i)),
"{}_{}_{}.{}".format(name, type_path, i, suffix)
)
slog.info("{}\t{}.{} {} save_ok".format(type_path, name, suffix, i))
if debug:
tmp = np.hstack((tmp, dst))
except Exception as e:
slog.error("{}\t{}.{}\t{}\t{}".format(type_path, name, suffix, i, e))
if debug:
cv2.imshow("con_bri_demo", tmp)
cv2.waitKey(0)
cv2.destroyAllWindows()
def gen_image_6(img, name, suffix, type_path="image_in_image"):
operator_list = [
[cv2.imread("./data/b1.jpg", cv2.IMREAD_COLOR), 0.5],
[cv2.imread("./data/b1.jpg", cv2.IMREAD_COLOR), 0.6],
[cv2.imread("./data/b2.jpg", cv2.IMREAD_COLOR), 0.4],
[cv2.imread("./data/b2.jpg", cv2.IMREAD_COLOR), 0.7],
[cv2.imread("./data/b3.jpg", cv2.IMREAD_COLOR), 0.3],
[cv2.imread("./data/b3.jpg", cv2.IMREAD_COLOR), 0.8],
[cv2.imread("./data/b4.jpg", cv2.IMREAD_COLOR), 0.4],
[cv2.imread("./data/b4.jpg", cv2.IMREAD_COLOR), 0.9],
[cv2.imread("./data/b5.jpg", cv2.IMREAD_COLOR), 0.5],
[cv2.imread("./data/b5.jpg", cv2.IMREAD_COLOR), 0.3],
]
if debug:
tmp = cv2.resize(operator_list[0][0], (512, 512))
for i, one in enumerate(operator_list):
try:
dst = image_in_image(img, one[0], one[1])
save_image(
dst,
os.path.join(save_path, type_path, str(i)),
"{}_{}_{}.{}".format(name, type_path, i, suffix)
)
slog.info("{}\t{}.{} {} save_ok".format(type_path, name, suffix, i))
if debug:
tmp = np.hstack((tmp, cv2.resize(dst, (512, 512))))
except Exception as e:
slog.error("{}\t{}.{}\t{}\t{}".format(type_path, name, suffix, i, e))
if debug:
cv2.imshow("con_bri_demo", tmp)
cv2.waitKey(0)
cv2.destroyAllWindows()
"""
tname = "t1"
tsuffix = "jpg"
path = "./data/{}.{}".format(tname, tsuffix)
img1 = cv2.imread(path, cv2.IMREAD_COLOR)
gen_images_1(cv2.imread(path, cv2.IMREAD_GRAYSCALE), tname, tsuffix)
# gen_images_2(img1, tname, tsuffix)
# gen_image_3(img1, tname, tsuffix)
# gen_image_4(img1, tname, tsuffix)
# gen_image_5(img1, tname, tsuffix)
# gen_image_6(img1, tname, tsuffix)
"""
root_path = "./ty"
# name_lists = [i for i in range(1, 60001)]
# random.shuffle(name_lists)
# time1 = time.time()
for one_image in os.listdir(root_path):
img = cv2.imread(os.path.join(root_path, one_image), cv2.IMREAD_COLOR)
img_name, suffix = one_image.split(".")
gen_images_1(cv2.imread(os.path.join(root_path, one_image), cv2.IMREAD_GRAYSCALE), img_name, suffix)
gen_images_2(img, img_name, suffix)
gen_image_3(img, img_name, suffix)
gen_image_4(img, img_name, suffix)
gen_image_5(img, img_name, suffix)
gen_image_6(img, img_name, suffix)
# print("all: {}s".format(time.time() - time1))
def check_image_size():
import cv2
import os
path = "./pics"
for one_image in os.listdir(path):
img = cv2.imread(os.path.join(path, one_image), cv2.IMREAD_COLOR)
w, h = img.shape[:2]
if w < 640 or h < 480:
print(os.path.join(path, one_image))
os.remove(os.path.join(path, one_image))