1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| import os import cv2 import pylab import random import numpy as np from skimage import io from matplotlib import pyplot as plt from PIL import Image, ImageFilter, ImageDraw
def gauss_noise(image, mean=0, var=0.001): ''' 添加高斯噪声 mean : 均值 var : 方差 ''' image = np.array(image/255, dtype=float) noise = np.random.normal(mean, var ** 0.5, image.shape) out = image + noise if out.min() < 0: low_clip = -1. else: low_clip = 0. out = np.clip(out, low_clip, 1.0) out = np.uint8(out*255) return out
def salt_and_pepper_noise(noise_img, proportion=0.1): height, width, _ = noise_img.shape num = int(height * width * proportion) for i in range(num): w = random.randint(0, width - 1) h = random.randint(0, height - 1) if random.randint(0, 1) == 0: noise_img[h, w] = 0 else: noise_img[h, w] = 255 return noise_img
''' 生成运动模糊图像 模糊距离10px '''
def motion_blur(image, degree=10, angle=45): image = np.array(image)
M = cv2.getRotationMatrix2D((degree / 2, degree / 2), angle, 1) motion_blur_kernel = np.diag(np.ones(degree)) motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M, (degree, degree))
motion_blur_kernel = motion_blur_kernel / degree blurred = cv2.filter2D(image, -1, motion_blur_kernel)
cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX) blurred = np.array(blurred, dtype=np.uint8) return blurred
''' 生成马赛克图像 :param rgb_img :param int x : 马赛克左顶点 :param int y: 马赛克左顶点 :param int w: 马赛克宽 :param int h: 马赛克高 :param int neighbor: 马赛克每一块的宽 '''
def do_mosaic(img, x, y, w, h, neighbor=9): for i in range(0, h , neighbor): for j in range(0, w , neighbor): rect = [j + x, i + y] color = img[i + y][j + x].tolist() left_up = (rect[0], rect[1]) x2=rect[0] + neighbor - 1 y2=rect[1] + neighbor - 1 if x2>x+w: x2=x+w if y2>y+h: y2=y+h right_down = (x2,y2) cv2.rectangle(img, left_up, right_down, color, -1) return img
def main():
path='./lena512color.tiff'
img=cv2.imread(path) lena_gauss=gauss_noise(img, mean=0,var=0.001) cv2.imwrite('./lena_gauss.png',lena_gauss) img = io.imread(path) lean_noise=salt_and_pepper_noise(img) io.imsave('./lena_noise.png',lean_noise)
img = cv2.imread(path) motion_img = motion_blur(img) cv2.imwrite('./lena_motion.png',motion_img)
im = Image.open(path) draw = ImageDraw.Draw(im) draw.rectangle((70, 100, 100, 130), fill=(0)) im.save('./lena_crop.png')
img=cv2.imread(path) lena_mosaic=do_mosaic(img, 200, 200, 200, 200, neighbor=10) cv2.imwrite('./lena_mosaic.png',lena_mosaic)
if __name__ == '__main__': main()
|