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

本文涉及的产品
实时计算 Flink 版,5000CU*H 3个月
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
大数据开发治理平台 DataWorks,不限时长
简介: 这篇文章介绍了使用NumPy进行图像处理的10个基本步骤,包括读取图像、缩小图像、水平和垂直翻转、旋转、裁剪、分离RGB通道、应用滤镜(如棕褐色调)、灰度化、像素化、二值化以及图像融合。通过这些简单的操作,读者可以更好地掌握NumPy在图像处理中的应用。示例代码展示了如何实现这些效果,并配有图像结果。文章强调这些方法适合初学者,更复杂的图像处理可使用专门的库如OpenCV或Pillow。

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

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

我们首先使用pillow读取图像

 import numpy as np

 #Use PIL to access image data
 from PIL import Image
 img = Image.open('monalisa.jpg')

 #Create array from image data 
 M = np.array(img)

 #Display array from image data 
 display(Image.fromarray(M))

1、缩小图像

 def reduce_image_size_by_n(image, n):

     # Get the height and width of the image
     height, width, channels = image.shape

     # Reduce the height and width by n
     new_height = height // n
     new_width = width // n

     # Create a new array to store the reduced image
     downsampled_image = np.zeros((new_height, new_width, channels), dtype=image.dtype)

     # Iterate over each pixel of the reduced image
     for i in range(new_height):
         for j in range(new_width):

             # Take every other pixel along each axis to reduce the image

             downsampled_image[i, j] = image[n*i, n*j]

     return downsampled_image

 #Try the function using n = 2

 reduced_M = reduce_image_size_by_n(M, 2)

 display(reduced_M)

2、水平翻转

 def flip_image(image):

   # Takes all rows in image (:) and reverses it the order of columns (::-1)
   flip_image = image[:, ::-1]
   return flip_image

 #Try function using reduced image
 display(flip_image(reduced_M))

3、垂直翻转

 def rotate_image (image, n):
   # rotate image using rot90, use n to determine number of rotation 
   rotated_img = Image.fromarray(np.rot90(image, k=n, axes=(1, 0)))
   return rotated_img

 #rotate image twice (n=2)
 display(rotate_image(reduced_M, 2))

4、裁剪图像

 def crop_image(image, crop_ratio, zoom_ratio):

   #create focused part using crop_ratio and zoom_ratio of choice

   top = image.shape[0] // crop_ratio 
   bottom = zoom_ratio * image.shape[0] // crop_ratio
   left = image.shape[1] // crop_ratio
   right = zoom_ratio * image.shape[1] // crop_ratio

   # Extract the focused part using array slicing
   focused_part = image[top:bottom, left:right]
   return focused_part

 display(crop_image(reduced_M, 4, 2))

5、RGB通道

 def RGB_image(image,image_color):

   if image_color == 'R':
     #make a copy of image for the color channel
     img_R = image.copy()
     #set other color channel to zero. Here Red is the first channel [0] 
     img_R[:, :, (1, 2)] = 0
     return img_R

   elif image_color == 'G':
     img_G = image.copy()
     #set other color channel to zero. Here Green is the second channel [1]
     img_G[:, :, (0, 2)] = 0
     return img_G

   elif image_color == 'B':
     img_B = image.copy()
     #set other color channel to zero. Here Blue is the third channel [2]
     img_B[:, :, (0, 1)] = 0
     return img_B

查看红色通道

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

 display(M_red)

绿色

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

 display(M_green)

蓝色

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

 display(M_blue)

6、应用滤镜

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

 def apply_sepia(image):
     # Sepia transformation matrix
     sepia_matrix = np.array([[0.393, 0.769, 0.189],
                              [0.349, 0.686, 0.168],
                              [0.272, 0.534, 0.131]])

     # Apply the sepia transformation
     sepia_img = image.dot(sepia_matrix.T)  # Using matrix multiplication

     # Ensure values are within valid range [0, 255]
     sepia_img = np.clip(sepia_img, 0, 255)

     return sepia_img.astype(np.uint8)

 # Apply sepia effect
 M_sepia = Image.fromarray(apply_sepia(reduced_M))

 display(M_sepia)

7、灰度化

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

 import numpy as np

 def grayscale(image):
     # Convert the RGB image to grayscale using weighted average
     grayscale_img = np.dot(image[..., :3], [0.2989, 0.5870, 0.1140])

     # Ensure values are within valid range [0, 255]
     grayscale_img = np.clip(grayscale_img, 0, 255)

     # Convert to uint8 data type
     grayscale_img = grayscale_img.astype(np.uint8)

     return grayscale_img

 # Convert the image to grayscale
 M_gray = grayscale(reduced_M)

 display(M_gray)

8、像素化

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

 def pixelate_image(image, block_size):

     # Determine the number of blocks in each dimension
     num_blocks_y = image.shape[0] // block_size
     num_blocks_x = image.shape[1] // block_size

     # Calculate the average color for each block
     block_means = np.zeros((num_blocks_y, num_blocks_x, 3), dtype=np.uint8)
     for y in range(num_blocks_y):
         for x in range(num_blocks_x):
             block = image[y * block_size: (y + 1) * block_size,
                         x * block_size: (x + 1) * block_size]
             block_mean = np.mean(block, axis=(0, 1))
             block_means[y, x] = block_mean.astype(np.uint8)

     # Upsample block means to original image size
     pixelated_image = np.repeat(np.repeat(block_means, block_size, axis=0), block_size, axis=1)

     return pixelated_image


 # Set the block size for pixelation (adjust as needed)
 block_size = 10

 # Pixelate the image
 M_pixelated = Image.fromarray(pixelate_image(reduced_M, block_size))

 display(M_pixelated)

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

9、二值化(Binarize)

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

 def binarize_image(image, threshold):

   #set pixel value greater than threshold to 255
   binarize_image = ((image > threshold) * 255).astype(np.uint8)

   return binarize_image

 #set threshold
 threshold = 68

 M_binarized = Image.fromarray(binarize_image(reduced_M, threshold))

 display(M_binarized)

10、图像融合

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

 #import and resize second image 

 img_2 = np.array(Image.open('Eiffel.jpg').resize(reduced_M.shape[1::-1]))  

 def blend_image(image1, image2, , visibility_2 ):

   #blend images by multiplying by visibility ratio for each image

   blend_image = (image1 * visibility_1 + image2 * visibility_2).astype(np.uint8)

   return blend_image



 modified_image = Image.fromarray(blend_image(reduced_M, img_2, 0.7, 0.3))

 display(modified_image)

总结

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

https://avoid.overfit.cn/post/da27bd78da0b4d76b639c0f9810fb6e0

作者:Ayo Akinkugbe

目录
相关文章
|
6天前
|
算法 计算机视觉 Python
图像处理与NumPy的完美结合
【4月更文挑战第17天】NumPy在Python图像处理中扮演重要角色,它支持高效的矩阵运算,使图像表示和操作变得简单。通过NumPy,可以方便地读取、显示图像,执行算术运算和滤波操作。此外,结合傅里叶变换和直方图均衡化等高级技术,NumPy能实现复杂图像处理任务,提升对比度和分析频率特性。其灵活性和效率为图像处理领域带来便利和进步。
|
6天前
|
机器学习/深度学习 存储 算法
OpenCV与NumPy:图像处理中的黄金组合
【4月更文挑战第17天】OpenCV和NumPy是Python图像处理的两大利器,互补协作形成黄金组合。OpenCV专注计算机视觉,提供丰富算法,而NumPy擅长数值计算和数组操作。两者无缝对接,共同实现高效、灵活的图像处理任务。通过灰度化、二值化、边缘检测等案例,展示了它们的协同作用。未来,这一组合将在计算机视觉和机器学习领域发挥更大作用,解锁更多图像处理潜力。
|
9月前
|
PHP 数据安全/隐私保护 计算机视觉
PHPImagine 图像处理库介绍
随着网络的发展,人们对图像的需求越来越高。作为一个PHP开发者,我们在处理图像时经常会遇到一些问题,比如裁剪、缩放、加水印等。这些问题都可以通过使用图像处理库来解决。PHPImagine就是一种优秀的图像处理库。
56 0
|
11月前
|
机器学习/深度学习 算法 自动驾驶
10个图像处理的Python库
在这篇文章中,我们将整理计算机视觉项目中常用的Python库,如果你想进入计算机视觉领域,可以先了解下本文介绍的库,这会对你的工作很有帮助。
156 1
|
11月前
|
计算机视觉 开发者 数据格式
Opencv(图像处理)-基于Python-绘图功能
Opencv(图像处理)-基于Python-绘图功能
99 0
|
Python
CV5 numpy入门及图像的基本操作
复制法,即复制最边缘的像素。
59 0
|
索引 Python
科学计算库Numpy-矩阵属性
科学计算库Numpy-矩阵属性
科学计算库Numpy-矩阵操作
科学计算库Numpy-矩阵操作
|
编解码 计算机视觉 Python
【图像处理】numpy打马赛克
经过上次对numpy简单的认识,相信家人们都非常想了解我们目前可以使用它做什么了 那么我们就举两个实战例子来进行说明 今天我们先以numpy打马为例 Are you ready?
118 0
【机器视觉】OpenCV-Python 图像的形态学操作
【机器视觉】OpenCV-Python 图像的形态学操作
66 0
【机器视觉】OpenCV-Python 图像的形态学操作