Image processing (1): Use Python to implement two methods of converting color images to grayscale images and convert pictures to grayscale images in batches

Introduction to two methods of converting color images to grayscale images using Python


Preface

This article mainly introduces Pythontwo methods of converting color images to grayscale images, as well as Pythona method of converting pictures to grayscale images in batches, for your reference:


1. The first method

Use the cv2 library in Python, which has its own method of converting color to grayscale, and the code is very simple.
First read a color picture, then display it in the window, then use cv2 to process it and convert it into a grayscale image. At this time it is a two-dimensional grayscale matrix, and finally convert it from array to image, and in another Displayed in the window, waitKey(0) keeps the window displayed, or you can write waitKey(300) to display the window for a period of time and then close it.

import cv2
from PIL import Image
#读取彩色图像
color_img = cv2.imread(r'E:/Pycharm/Python/DS-05.jpg')
# 预处理操作,将输入图像变成300×300,不需要可以删除
reImg = cv2.resize(color_img, (300, 300), interpolation=cv2.INTER_CUBIC)
# 在窗口中显示图像
cv2.imshow('Resize image',reImg)
#cvtColor的第一个参数是处理的图像,第二个是RGB2GRAY
gray_img=cv2.cvtColor(reImg,cv2.COLOR_RGB2GRAY)
#gray_img为二维矩阵表示,要实现array到image的转换
gray=Image.fromarray(gray_img)
#将图片保存到当前路径下,参数为保存的文件名
gray.save('gray.jpg')
cv2.imshow('Gray Image',gray_img)
#如果想让窗口长时间停留,使用该函数 cv2.waitKey(0)
cv2.waitKey(300)

The result is as follows:
Insert image description here
Insert image description here

2. The second method

Use the Image library in PIL, and then use pyplot to display it on the canvas. The code is as follows:

from PIL import Image
from matplotlib import pyplot as plt

color_img = Image.open('E:/Pycharm/Python/DS-05.jpg')
# 转换成灰度图像
gray_img = color_img.convert('L')
print_res = 'gray'
plt.figure('DS')
#plt.figure(num=1, figsize=(8,5),)
plt.imshow(gray_img, cmap='gray')
# 命名标题
plt.title(print_res)
# 不显示坐标轴
plt.axis('off')
plt.show()

The result is as follows:
Insert image description here

3. Python converts images to grayscale in batches

code show as below:

from PIL import Image
import os
path = 'E:/Pycharm/Python/图片'
file_list = os.listdir(path)
# 循环
for image in file_list:
    I = Image.open(path + "/" + image)
    gray = I.convert('L')
    gray.save(path + "/" + image)
    #print(file)

Summarize

The above is what I have written this time. This article only briefly introduces the method of converting color images into grayscale images. I will continue to write articles about image processing using Python in the future. If you like it, please like and collect it.

Guess you like

Origin blog.csdn.net/qq_44368508/article/details/126419058