PIL+Numpy+Matplotlib realizes image processing

PIL library installation

ImageModule is PILan important module in the library, it can help us realize image processing

But PILthe library Pythonis not built in, you need to install it by typing the following in
the console ( ) :cmdPIL

pip install Pillow

In this article, we need to use 3 libraries, and the installation commands are as follows:

pip install Pillow numpy matplotlib

Students who feel slow can add parameters:

pip install Pillow numpy matplotlib -i https://pypi.doubanio.com/simple

Image module common functions

function name meaning and function
Image.open(file) Open the specified image file and recognize, for example: img = Image.open(test.png), it means to open test.pngand assign to imgthe object
img.show() Display an image of the specified object
img.format get image format
img.size View the size of the image in the format (width, height). Unit: Pixel
img.heightandimg.width View the height and width of the image separately
img.save(file) save as new image
img.rotate(x) Rotation x_
img.mode Get the color mode of an image
img.resize((x,y)) Scale the image, the parameter indicates the new size (width and height) of the image. Unit: Pixel

display image information

After installing the three libraries, we can start processing images

First import the module, pay attention Imageto Iuppercase

from PIL import Image

Then, read in the image and assign it to imgthe object

img = Image.open("test.png")

You can take this picture as a sample:
bee
Next, get the image file format

print(img.format) # 查看图像文件格式

get image size

print(img.size) # 查看图像尺寸

get image of颜色模式

print(img.mode) # 查看图像的颜色模式

The integration code is as follows:

from PIL import Image
img = Image.open("test.png")
print(img.format) # 查看图像文件格式
print(img.size) # 查看图像尺寸
print(img.mode) # 查看图像的颜色模式

Run the screenshot:

Rotation angle

Full code:

from PIL import Image
img = Image.open("test.png")
img = img.rotate(90) # img.rotate(90).show()
img.show()

Of course, you can also let the user input how many degrees to rotate

from PIL import Image
img = Image.open("test.png")
angle = int(input("请输入旋转的角度:"))
img.rotate(angle).show()

Color image to black and white

At this time, matplotlibthe numpylibrary will be used

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

Open the image and convert to a grayscale matrix

img = np.array(Image.open("test.png").convert('L'))

Among them, convert()the function is used for conversion between images in different modes. The mode Lis a grayscale image, and each pixel of it is 8个bitrepresented by .

In PILthe library, RGBthe conversion from mode to Lis converted according to the following formula:
L = R × 299 ÷ 1000 + G × 587 ÷ 1000 + B × 114 ÷ 1000 L = R×299÷1000+G×587÷1000+B× 114÷1000L=R×299÷1000+G×587÷1000+B×114÷1000

Then, transform RGBthe value of each pixel

width, height = img.shape # 图像尺寸分别赋值
for i in range(width):
    for j in range(height):
        if(img [i,j] > 128):
            img [i,j] = 1
        else:
            img [i,j] = 2

generate a new image and display

plt.figure("Image") # 标题
plt.imshow(img, cmap = 'gray') # 显示灰度图像
plt.axis('off') # 关闭图像坐标
plt.show()

The integration code is as follows:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

img = np.array(Image.open("test.png").convert('L'))
width, height = img.shape # 图像尺寸分别赋值
for i in range(width):
    for j in range(height):
        if(img [i,j] > 128):
            img [i,j] = 1
        else:
            img [i,j] = 0
            
plt.figure("Image") # 标题
plt.imshow(img, cmap = 'gray') # 显示灰度图像
plt.axis('off') # 关闭图像坐标
plt.show()

Well, the effect is not very good
, so I made an enhanced version, the user can enter the path by himself, or adjust the specific value for converting black and white.
The code is as follows:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

path = input("输入路径: ")
ipath = input("输入图片名: ")
img = np.array(Image.open(path+ "/" +ipath).convert('L'))

num = float(input("输入特定值: "))
rows, cols = img.shape
for i in range(rows):
    for j in range(cols):
        if(img [i,j] > num):
            img [i,j] = 1
        else:
            img [i,j] = 0

plt.figure("Image")
plt.imshow(img, cmap = 'gray')
plt.axis('off')
plt.show()

Well, much better
I found peace of mind

Color Image to Grayscale

This is relatively simple, just go to the code

from PIL import Image

img = Image.open("test.png").convert('L').show()


Guess you like

Origin blog.csdn.net/weixin_45122104/article/details/126292177