Untitled
user_2381398
plain_text
3 years ago
1.6 kB
9
Indexable
import cv2
import numpy as np
import os
# Step 1: Load images
image_path = "./image"
out_noise_path = "./noise_image"
# Size of pixelized block
block_size = 8
# Check output path integrity
if not os.path.exists(out_noise_path):
os.mkdir(out_noise_path)
def pixelize_and_add_noise(image, block_size):
row, col, ch = image.shape
noisy_image = np.copy(image)
for i in range(0, row, block_size):
for j in range(0, col, block_size):
# Pixelization: use the mean value for each block
block_mean = np.mean(noisy_image[i:i+block_size, j:j+block_size], axis=(0, 1))
noisy_image[i:i+block_size, j:j+block_size] = block_mean
# Randomly generate the noise RGB values
noise = np.random.randint(0, 50, (ch,))
# Add the noise to the block
noisy_image[i:i+block_size, j:j+block_size] += noise
# Clip values to be in valid range 0-255
noisy_image = np.clip(noisy_image, 0, 255)
return noisy_image
for image_path1 in os.listdir(image_path):
for image_path2 in os.listdir(image_path+"/"+image_path1):
image = cv2.imread(image_path+"/"+image_path1+"/"+image_path2)
# Step 2: Pixelize and add noise to image
noisy_image = pixelize_and_add_noise(image, block_size)
# Step 3: Save the noisy image
# Check path integrity
if not os.path.exists(out_noise_path+"/"+image_path1):
os.mkdir(out_noise_path+"/"+image_path1)
cv2.imwrite(out_noise_path+"/"+image_path1+"/"+image_path2, noisy_image)
Editor is loading...