Is my noise function differentially private? Is flattening then reshaping correct? Or it breaks the image?
21:24 30 Dec 2025

The main function is apply_noise which applies the noise using the laplacian distribution, the scale of the distribution is b which is calculated with an epsilon value and the sensitivity value that comes from the function calculate_sensitivity.

def calculate_sensitivity(image: np.ndarray) -> float:
    if image.ndim > 1:
        d = image.flatten()
    else:
        d = image
    d_f = np.mean(d)
    deviations_of_d = np.abs(d - d_f)
    furthest_of_d = np.max(deviations_of_d)
    argmax_furthest_of_d = np.where(deviations_of_d == furthest_of_d)[0][0]

    dprime = np.delete(d, argmax_furthest_of_d)
    dprime_f = np.mean(dprime)

    return abs(d_f - dprime_f)

def apply_noise(image: np.ndarray, epsilon: float) -> np.ndarray:
    image = image.flatten()
    sensibility = calculate_sensitivity(image)
    b = sensibility / epsilon
    noise = np.random.laplace(0, b, image.shape)
    output = image + noise
    clip_output = np.clip(output, 0, 1) # -1, 1 for facenet
    return clip_output.reshape((160, 160, 3)) 

It seems to work, as you can see bellow:

Images with noise given different values of epsilon

I do think it works, but I'm not quite sure if it is the correct approach. I'm applying noise to an image with more than 1 channel and using the flatten() function to calculate the sensitivity of the image more easily, later on i use the reshape() function to bring the image back to its original shape. Is this correct? Or should i apply the noise to each channel individually?

Even if i do apply the noise individually to each channel, wouldn't i need to flatten the image? For example an image with (C, H, W) = (3, 160, 160), if i apply the noisy to each channel i would still need to flatten the height and the width. So the problem would be the same.

python numpy image-processing noise