Untitled

 avatar
user_2381398
plain_text
6 months ago
1.6 kB
2
Indexable
Never
import cv2
import os

# Step 1: Load images
image_path = "./image"
out_noise_path = "./noise_image"

# Size of pixelized block
block_size = 8

# Specified noise RGB value
noise_value = [10, 10, 10]

# 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, noise_value):
    row, col, ch = image.shape
    noisy_image = image.copy()

    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 = noisy_image[i:i+block_size, j:j+block_size].mean(axis=(0, 1))
            noisy_image[i:i+block_size, j:j+block_size] = block_mean

            # Add the specified noise to the block
            noisy_image[i:i+block_size, j:j+block_size] += noise_value
            
    # Clip values to be in valid range 0-255
    noisy_image = np.clip(noisy_image, 0, 255).astype('uint8')
            
    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, noise_value)

        # 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)