thonypythony's picture
scripts for create a dataset
2eee9d6 verified
'''
DATASET/:
test/:
0/ # without watermark
1/ # with
train/:
0/
1/
validation/:
0/
1/
'''
# pip install opencv-python
# pip install PyWavelets
from blind_watermark import WaterMark
from PIL import Image
import os, sys, PIL, shutil, time, glob
from numpy.random import randint
def renameimg(path):
os.getcwd()
for i, filename in enumerate(os.listdir(path)):
try:
os.rename(path + "/" + filename, path + "/" + str(i) + ".jpeg")
except FileExistsError:
pass
def resize(path, color_mode):
dirs = os.listdir(path)
print('before resize ', len(dirs))
for item in dirs:
try:
# print(item)
with Image.open(fr'{path}/{item}') as im:
resized = im.convert(f'{color_mode}').resize((Width,Height))
resized.save(fr'{path}/{item}')
time.sleep(0.0003)
# print(fr'for {item} have been done')
except PIL.UnidentifiedImageError:
print(fr"Confirmed: This image {path}/{item} cannot be opened!")
# os.remove(f'{path}{item}')
except OSError:
im = Image.open(fr'{path}/{item}').convert(f'{color_mode}').resize((Width,Height))
im.save(fr'{path}/{item}')
print(fr"Chanched by hands for {path}/{item}")
dirs = os.listdir(path)
print('after resize ', len(dirs))
def moveimg(fromdir, todir, STOP):
for i, filename in enumerate(os.listdir(fromdir)):
if i == STOP:
break
else:
shutil.move(fromdir + "/" + filename, todir + "/" + filename)
i += 1
def lenght_watermark(img_name, watermark, passwordwm=1):
bwm1 = WaterMark(password_img=1, password_wm=passwordwm) # mode='common' vs mode='multithreading'
bwm1.read_img(f'{img_name}')
bwm1.read_wm(watermark, mode='str')
len_wm = len(bwm1.wm_bit)
return len_wm
def embed_watermark(img_name, watermark, passwordwm=1, compression_ratio=100, d1 = 9, d2 = 7, fast_mode = True, n = 3):
bwm1 = WaterMark(password_img=1, password_wm=passwordwm, mode='common', d1 = d1, d2 = d2, fast_mode = fast_mode, n = n)
bwm1.read_img(f'{img_name}')
bwm1.read_wm(watermark, mode='str')
bwm1.embed(f'{img_name}', compression_ratio=compression_ratio)
Width, Height = 512, 256
path = "COCO"
color_mode = "RGB"
# renameimg(path)
# resize(path, color_mode)
src = 'COCO'
train_list = ['DATASET/train/0', 'DATASET/train/1']
# for dst in train_list:
# moveimg(src, dst, 37020)
validation_and_test_list = ['DATASET/validation/0', 'DATASET/validation/1', 'DATASET/test/0', 'DATASET/test/1']
# for dst in validation_and_test_list:
# moveimg(src, dst, 12340)
image_with_wm = ['DATASET/train/1', 'DATASET/validation/1', 'DATASET/test/1']
times = 4
for paths in image_with_wm:
count = len(os.listdir(paths))
print(f'current count = {count}')
os.chdir(f"{paths}/")
print('current directory = ', os.getcwd())
images = glob.glob("*.jpeg")
for name in images:
# print(name)
password_wm = randint(1,999999999)
wm = str(randint(1000000,9999999))
d1 = d2 = randint(1,9)
block_size = randint(1,5)
embed_watermark(name, wm*times, password_wm, d1 = d1, d2 = d2, n = block_size)
count -= 1
if count % 10 == 0:
print(f'current count = {count}')