0


10个使用NumPy就可以进行的图像处理步骤

图像处理是一种数学计算。数字图像由称为像素的彩色小点组成。每个像素由红、绿、蓝(RGB)三个独立的颜色组成。每个像素中的主色由每个RGB分量的数值决定。

本文将介绍10个使用使用NumPy就可以进行的图像处理步骤,虽然有更强大的图像处理库,但是这些简单的方法可以让我们更加熟练的掌握NumPy的操作。

我们首先使用pillow读取图像

  1. import numpy as np
  2. #Use PIL to access image data
  3. from PIL import Image
  4. img = Image.open('monalisa.jpg')
  5. #Create array from image data
  6. M = np.array(img)
  7. #Display array from image data
  8. display(Image.fromarray(M))

1、缩小图像

  1. def reduce_image_size_by_n(image, n):
  2. # Get the height and width of the image
  3. height, width, channels = image.shape
  4. # Reduce the height and width by n
  5. new_height = height // n
  6. new_width = width // n
  7. # Create a new array to store the reduced image
  8. downsampled_image = np.zeros((new_height, new_width, channels), dtype=image.dtype)
  9. # Iterate over each pixel of the reduced image
  10. for i in range(new_height):
  11. for j in range(new_width):
  12. # Take every other pixel along each axis to reduce the image
  13. downsampled_image[i, j] = image[n*i, n*j]
  14. return downsampled_image
  15. #Try the function using n = 2
  16. reduced_M = reduce_image_size_by_n(M, 2)
  17. display(reduced_M)

2、水平翻转

  1. def flip_image(image):
  2. # Takes all rows in image (:) and reverses it the order of columns (::-1)
  3. flip_image = image[:, ::-1]
  4. return flip_image
  5. #Try function using reduced image
  6. display(flip_image(reduced_M))

3、垂直翻转

  1. def rotate_image (image, n):
  2. # rotate image using rot90, use n to determine number of rotation
  3. rotated_img = Image.fromarray(np.rot90(image, k=n, axes=(1, 0)))
  4. return rotated_img
  5. #rotate image twice (n=2)
  6. display(rotate_image(reduced_M, 2))

4、裁剪图像

  1. def crop_image(image, crop_ratio, zoom_ratio):
  2. #create focused part using crop_ratio and zoom_ratio of choice
  3. top = image.shape[0] // crop_ratio
  4. bottom = zoom_ratio * image.shape[0] // crop_ratio
  5. left = image.shape[1] // crop_ratio
  6. right = zoom_ratio * image.shape[1] // crop_ratio
  7. # Extract the focused part using array slicing
  8. focused_part = image[top:bottom, left:right]
  9. return focused_part
  10. display(crop_image(reduced_M, 4, 2))

5、RGB通道

  1. def RGB_image(image,image_color):
  2. if image_color == 'R':
  3. #make a copy of image for the color channel
  4. img_R = image.copy()
  5. #set other color channel to zero. Here Red is the first channel [0]
  6. img_R[:, :, (1, 2)] = 0
  7. return img_R
  8. elif image_color == 'G':
  9. img_G = image.copy()
  10. #set other color channel to zero. Here Green is the second channel [1]
  11. img_G[:, :, (0, 2)] = 0
  12. return img_G
  13. elif image_color == 'B':
  14. img_B = image.copy()
  15. #set other color channel to zero. Here Blue is the third channel [2]
  16. img_B[:, :, (0, 1)] = 0
  17. return img_B

查看红色通道

  1. M_red = Image.fromarray(RGB_image(reduced_M, 'R'))
  2. display(M_red)

绿色

  1. M_green = Image.fromarray(RGB_image(reduced_M, 'G'))
  2. display(M_green)

蓝色

  1. M_blue = Image.fromarray(RGB_image(reduced_M, 'B'))
  2. display(M_blue)

6、应用滤镜

这里使用棕褐色(Sepia)作为示例,可以根据不同的要求修改转换矩阵

  1. def apply_sepia(image):
  2. # Sepia transformation matrix
  3. sepia_matrix = np.array([[0.393, 0.769, 0.189],
  4. [0.349, 0.686, 0.168],
  5. [0.272, 0.534, 0.131]])
  6. # Apply the sepia transformation
  7. sepia_img = image.dot(sepia_matrix.T) # Using matrix multiplication
  8. # Ensure values are within valid range [0, 255]
  9. sepia_img = np.clip(sepia_img, 0, 255)
  10. return sepia_img.astype(np.uint8)
  11. # Apply sepia effect
  12. M_sepia = Image.fromarray(apply_sepia(reduced_M))
  13. display(M_sepia)

7、灰度化

灰度化可以简单的理解为将RBG三个通道合并成一个黑白的通道

  1. import numpy as np
  2. def grayscale(image):
  3. # Convert the RGB image to grayscale using weighted average
  4. grayscale_img = np.dot(image[..., :3], [0.2989, 0.5870, 0.1140])
  5. # Ensure values are within valid range [0, 255]
  6. grayscale_img = np.clip(grayscale_img, 0, 255)
  7. # Convert to uint8 data type
  8. grayscale_img = grayscale_img.astype(np.uint8)
  9. return grayscale_img
  10. # Convert the image to grayscale
  11. M_gray = grayscale(reduced_M)
  12. display(M_gray)

8、像素化

像素是一个一个色块组成的,像素化顾名思义就是将图像分成一定的区域,并将这些区域转换成相应的色块,再有色块构成图形。类似于色彩构图。简单来说,就是把矢量图形转换成像素点组成的点阵图形,也叫栅格化。

  1. def pixelate_image(image, block_size):
  2. # Determine the number of blocks in each dimension
  3. num_blocks_y = image.shape[0] // block_size
  4. num_blocks_x = image.shape[1] // block_size
  5. # Calculate the average color for each block
  6. block_means = np.zeros((num_blocks_y, num_blocks_x, 3), dtype=np.uint8)
  7. for y in range(num_blocks_y):
  8. for x in range(num_blocks_x):
  9. block = image[y * block_size: (y + 1) * block_size,
  10. x * block_size: (x + 1) * block_size]
  11. block_mean = np.mean(block, axis=(0, 1))
  12. block_means[y, x] = block_mean.astype(np.uint8)
  13. # Upsample block means to original image size
  14. pixelated_image = np.repeat(np.repeat(block_means, block_size, axis=0), block_size, axis=1)
  15. return pixelated_image
  16. # Set the block size for pixelation (adjust as needed)
  17. block_size = 10
  18. # Pixelate the image
  19. M_pixelated = Image.fromarray(pixelate_image(reduced_M, block_size))
  20. display(M_pixelated)

更通俗的的讲就是我的世界风格的图像

9、二值化(Binarize)

二值化是将数值型特征取值阈值化转换为布尔型特征取值,或者通俗的讲就是设定一个阈值,超过阈值设置成ture,否则设置成false

  1. def binarize_image(image, threshold):
  2. #set pixel value greater than threshold to 255
  3. binarize_image = ((image > threshold) * 255).astype(np.uint8)
  4. return binarize_image
  5. #set threshold
  6. threshold = 68
  7. M_binarized = Image.fromarray(binarize_image(reduced_M, threshold))
  8. display(M_binarized)

10、图像融合

最简单的图像同和方法就是根据不同的透明度,对2张图象的像素求和相加,如下所示

  1. #import and resize second image
  2. img_2 = np.array(Image.open('Eiffel.jpg').resize(reduced_M.shape[1::-1]))
  3. def blend_image(image1, image2, , visibility_2 ):
  4. #blend images by multiplying by visibility ratio for each image
  5. blend_image = (image1 * visibility_1 + image2 * visibility_2).astype(np.uint8)
  6. return blend_image
  7. modified_image = Image.fromarray(blend_image(reduced_M, img_2, 0.7, 0.3))
  8. display(modified_image)

总结

对于图像的操作其实就是对于图像进行数组操作的过程,我们这里展示的一些简单的操作只是为了熟悉Numpy的操作,如果需要更加专业的操作请使用更加专业的库,例如OpenCV或者Pillow。

作者:Ayo Akinkugbe

“10个使用NumPy就可以进行的图像处理步骤”的评论:

还没有评论