删除图像的一部分是什么意思? 在数学和编程上,大多数时候,这意味着将图像对应区域的数组转换为(0,0,0) 表示 RGB 通道值,或黑色。
在许多情况下,删除图像的一部分很有用。 比如在文字转图片应用中,使用Dallie2,我们可以通过AI修复来编辑图像的一部分。而重新智能生成新图片的准备工作就是把需要修改的部分先删掉。
使用 Python 图像库进行图像处理
from PIL import Image
import numpy as np
# Opening the image and converting
# it to RGB color mode
img = Image.open("lena.png").convert('RGB')
display(img)
# Extracting the image data &
# creating an numpy array out of it
img_arr = np.array(img)
# check the pixel size of this image
print(img_arr.shape)
# check some of the values
img_arr
(225, 400, 3)
array([[[108, 73, 53],
[109, 72, 54],
[109, 67, 51],
...,
[ 56, 41, 44],
[ 62, 47, 50],
[ 70, 54, 57]],
[[110, 75, 55],
[110, 73, 55],
[109, 67, 51],
...,
[ 54, 39, 42],
[ 57, 42, 45],
[ 64, 48, 51]],
[[109, 74, 55],
[110, 73, 55],
[107, 68, 53],
...,
[ 51, 39, 41],
[ 56, 41, 44],
[ 61, 46, 49]],
...,
[[130, 75, 54],
[128, 74, 50],
[130, 78, 56],
...,
[123, 75, 61],
[122, 74, 60],
[128, 80, 66]],
[[129, 72, 52],
[127, 70, 50],
[131, 77, 53],
...,
[126, 78, 64],
[122, 74, 60],
[126, 78, 64]],
[[134, 72, 49],
[133, 72, 51],
[126, 71, 51],
...,
[140, 87, 71],
[135, 79, 64],
[140, 84, 67]]], dtype=uint8)
从以上结果可以看出,图像有 225(y 方向)乘以 400(x 方向)像素; 在每个像素处,有一个大小为 3 的元组代表 RGB 颜色。
需要注意的一件事是 RGB 和 RGBA 之间的通道差异。 如果您拍摄屏幕快照。 边界框内的像素在 Windows 上作为“RGB”图像返回,在 macOS 上作为“RGBA”图像返回。 对于 RGB 通道,它需要 24 位来编码像素,而对于 RGBA,它需要 32 位来编码像素。
如果原始图像有RGB通道,但我们需要RGBA通道,我们可以使用下面的函数将图像从RGB通道转换为RGBA通道,反之亦然。
img_rgba = Image.open("lena.jpg").convert('RGBA')
img_arr_rgba = np.array(img_rgba)
# check the pixel size of this new image
print(img_arr_rgba.shape)
(225, 400, 4)
让我们回到删除部分图像的任务,如下所示
# Turning part of the the pixel values of to be black
# the order is ymin: ymax, xmin:xmax
img_arr[150 : 225, 0 : 100] = (0, 0, 0)
# Creating an image out of the previously modified array
img_edit = Image.fromarray(img_arr)
# Displaying the image
display(img_edit)
现在您可以看到图像的左角现在是黑色的。