a year ago
1.9 kB
import cv2
import os
import numpy as np  # 這行代碼導入了 numpy

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

def pixelize_and_add_noise(image, block_size, noise_value):
    row, col, ch = image.shape
    noisy_image = image.astype('int64')  # Convert to int64 before adding noise

    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')  # Convert back to uint8 after adding noise
    return noisy_image

for image_path1 in os.listdir(image_path):
    if os.path.isdir(os.path.join(image_path, image_path1)):
        for image_path2 in os.listdir(os.path.join(image_path, image_path1)):
            image = cv2.imread(os.path.join(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(os.path.join(out_noise_path, image_path1)):
                os.mkdir(os.path.join(out_noise_path, image_path1))
            cv2.imwrite(os.path.join(out_noise_path, image_path1, image_path2), noisy_image)