import os
from PIL import Image
import glob
import numpy as np
outdir = r'C:\Users\admin\Desktop\c1\dama'
count = 0
for i in glob.glob(r'C:\Users\admin\Desktop\c1\resize/*.jpg'):
im1 = Image.open(i)
arr = np.array(im1)
h = arr.shape[0]
w = arr.shape[1]
a = 7
for m in range(a): #每张图可以生成a张打码图
im2 = im1.copy() #同一张每次取出都复制,以防上次操作影响到下次
for j in range(int((m/a) * w),int(((m+1)/a) * w),1):#每个m对应一段x
for k in range(int(h-(m/a)*h - 1),int(h-((m+1)/a)*h - 1),-1):
im2.putpixel((j, k), (255,0,0)) # 这些像素点的颜色改成红色,改了图本身
if m>0 and m 0 and m < a - 1:
count += 1
print(count)
im3.save(os.path.join(outdir, '{}.jpg'.format(count)))
im4 = im1.copy()
for e in range(int((m / a) * w), int(((m + 1) / a) * w), 1):
for f in range(int(h/2 - 1/2 * (1 /a) * w), int(h/2 + 1/2 * (1 /a) * w), 1):
im4.putpixel((e, f), (255, 0, 0))
if m > 0 and m < a - 1:
count += 1
print(count)
im4.save(os.path.join(outdir, '{}.jpg'.format(count)))
import os
from PIL import Image
import numpy as np
outdir = r'C:\Users\admin\Desktop\c1\trainB'
count = 0
path = r'C:\Users\admin\Desktop\c1\trainA'
x_names = os.listdir(path)
x_names.sort(key=lambda i:int(i[:-4]))
for i in x_names:
im1 = Image.open(os.path.join(path,i))
arr = np.array(im1)
h = arr.shape[0]
w = arr.shape[1]
for j in range(int((1 / 3) * w), int((2 / 3) * w), 1):
for k in range(int((1 / 3) * h), int((2 / 3) * h), 1):
im1.putpixel((j, k), (255, 0, 0))
count += 1
print(count)
im1.save(os.path.join(outdir, '{}.jpg'.format(count)))
import os
from PIL import Image
import glob
import numpy as np
outdir = r'C:\Users\admin\Desktop\c1\dama'
count = 0
for i in glob.glob(r'C:\Users\admin\Desktop\c1\img/*.jpg'):
im1 = Image.open(i)
arr = np.array(im1)
'在此也能体会到:若是要读取图片的尺寸等属性,最好直接用cv2,而不是PIL或matplotlib'
# h = im1.shape[0]#错,im1作为图片,本身没有shape等np矩阵属性,故需先图转矩阵
# w = im1.shape[1]
h = arr.shape[0]
w = arr.shape[1]
a = 9
for j in range(int(1 / 4 * w), int(3 / 4 * w), a):
for k in range(int(1 / 4 * w), int(3 / 4 * w), a):
arr[j:j + a, k:k + a] = arr[j + (a // 2)][k + (a // 2)]
count += 1
print(count)
im2 = Image.fromarray(arr)
im2.save(os.path.join(outdir,os.path.basename(i)))
效果如下(顺序因其他操作给打乱了)
注:我是直接对celeba数据集人脸做了打码处理。其中第18、19行的系数和depts值,要根据具体图片尺寸以及你想要打码的区域,自行作出改动。
1.cv2按BGR读取,以下是未做转RGB操作的效果
2.正确操作,效果如下