python simple image processing based on numpy array


python simple image processing based on numpy array

As shown in the figure, take the cat picture as an example (ignore the watermark). Name the file cat.jpg and expand it with the following actions.
insert image description here


Grayscale using the PIL library

from PIL import Image
import numpy as np

# 读取图像,并转化为数组
im = np.array(Image.open("cat.jpg"))

# 灰度处理公式
gray_narry = np.array([0.299, 0.587, 0.114])
x = np.dot(im, gray_narry)

# 数组转图片
gray_cat = Image.fromarray(x.astype('uint8'))
# 保存图片
gray_cat.save('gray_cat.jpg')
# 展示查看
gray_cat.show()

Processed successfully!
insert image description here


rotate it 180 degrees

The so-called rotation operation means that the data in the three-dimensional array is arranged in reverse order in units of each row (three).

from PIL import Image
import numpy as np

# 读取图像,并转化为数组
im = np.array(Image.open("cat.jpg"))
# 旋转
x = im[::-1]

# 数组转图片
cat2 = Image.fromarray(x.astype('uint8'))
# 保存图片
cat2.save('cat2.jpg')
# 展示查看
cat2.show()

Program execution result:
insert image description here


Grayscale processing is done using the matplotlib library

import numpy as np
import matplotlib.pyplot as plt
n1 = plt.imread("cat.jpg")  # 读取了图片,转化为数组,三维的
plt.imshow(n1)
n2 = np.array([0.299, 0.587, 0.114])
x = np.dot(n1, n2)
plt.imshow(x, cmap="gray")
plt.show()

insert image description here


Guess you like

Origin blog.csdn.net/weixin_48964486/article/details/123745510