Untitled

 avatar
user_2381398
plain_text
a year ago
1.5 kB
2
Indexable
Never
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 add_block_noise(image, block_size):
    row, col, ch = image.shape
    row_pad = block_size - row % block_size
    col_pad = block_size - col % block_size

    image_padded = np.pad(image, ((0, row_pad), (0, col_pad), (0, 0)), mode='constant')
    noisy_image = np.copy(image_padded)

    for i in range(0, row, block_size):
        for j in range(0, col, block_size):
            block = noisy_image[i:i+block_size, j:j+block_size]
            gauss = np.random.randn(*block.shape)
            noisy_image[i:i+block_size, j:j+block_size] = block + block * gauss
            
    return noisy_image[:row, :col]

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: Add noise to image
        noisy_image = add_block_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)