def add_noise(image, epsilon, k): f = np.fft.fft2(image) fshift = np.fft.fftshift(f) rows, cols = image.shape b = laplas(fshift, epsilon, k) # print(b) p = 0.5 noise = np.random.laplace(scale=b, size=(rows, cols)) + np.mean(f) * p image_noise = fshift + noise f_ishift = np.fft.ifftshift(image_noise) image_back = np.fft.ifft2(f_ishift) image_back = np.real(image_back) return image_back def laplas(FIM, epsilon, k): FIM_k = FIM[:k, :k] sensitivity = np.abs(FIM_k) / np.sqrt(epsilon) sensitivity2 = np.abs(FIM) / np.sqrt(epsilon) scale = sensitivity2 / epsilon delta_f = np.max(np.sqrt(np.real(FIM[:k, :k]) ** 2 + np.imag(FIM[:k, :k]) ** 2)) - np.min( np.sqrt(np.real(FIM[:k, :k]) ** 2 + np.imag(FIM[:k, :k]) ** 2)) c = delta_f / epsilon d = delta_f * math.sqrt(2 * math.log(1.2 / 0.1)) / epsilon return d def add_noisy_image(): image = cv2.imread("image.jpg", cv2.IMREAD_GRAYSCALE) image = cv2.resize(image, (128, 128), interpolation=cv2.INTER_LINEAR) epsilon = 0.3 k = 50 image_back = add_noise(image, epsilon, k) im = cv2.resize(image_back, (47, 62), interpolation=cv2.INTER_LINEAR) image_back = np.uint8(im) cv2.imwrite("face_privacy.jpg", image_back) return image_back
时间: 2023-12-26 13:03:16 浏览: 134
以下是将三个函数合并成一个函数的代码:
```python
def add_noisy_image(image_path, output_path, epsilon=0.3, k=50):
# 读取图片并调整大小
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, (128, 128), interpolation=cv2.INTER_LINEAR)
# 对图片添加噪声
f = np.fft.fft2(image)
fshift = np.fft.fftshift(f)
rows, cols = image.shape
FIM = fshift
FIM_k = FIM[:k, :k]
delta_f = np.max(np.sqrt(np.real(FIM[:k, :k]) ** 2 + np.imag(FIM[:k, :k]) ** 2)) - np.min(np.sqrt(np.real(FIM[:k, :k]) ** 2 + np.imag(FIM[:k, :k]) ** 2))
c = delta_f / epsilon
d = delta_f * math.sqrt(2 * math.log(1.2 / 0.1)) / epsilon
sensitivity = np.abs(FIM_k) / np.sqrt(epsilon)
sensitivity2 = np.abs(FIM) / np.sqrt(epsilon)
scale = sensitivity2 / epsilon
b = d * scale
p = 0.5
noise = np.random.laplace(scale=b, size=(rows, cols)) + np.mean(f) * p
image_noise = fshift + noise
f_ishift = np.fft.ifftshift(image_noise)
image_back = np.fft.ifft2(f_ishift)
image_back = np.real(image_back)
# 调整大小并保存图片
im = cv2.resize(image_back, (47, 62), interpolation=cv2.INTER_LINEAR)
image_back = np.uint8(im)
cv2.imwrite(output_path, image_back)
return image_back
```
这个函数接收三个参数:输入图片路径、输出图片路径、epsilon 和 k。其中,epsilon 和 k 用于调整噪声的强度和频率范围。在函数内部,首先读取输入图片并调整大小,然后对图片进行处理生成噪声图像。最后,将生成的噪声图像调整大小并保存到指定路径,返回生成的噪声图像。
使用这个函数时,可以像下面这样调用:
```python
add_noisy_image('image.jpg', 'face_privacy.jpg', epsilon=0.3, k=50)
```
阅读全文