In Python, we can use an OpenCV library named cv2. Python does not come with cv2, so we need to install it separately.
在Python中,我们可以使用名为cv2的OpenCV库 。 Python没有随附cv2 ,因此我们需要单独安装它。
For Windows:
对于Windows:
pip install opencv-python
For Linux:
对于Linux:
sudo apt-get install python-opencv
In the below given program, we are using following three functions:
在下面给出的程序中,我们使用以下三个功能:
imread():
imread():
It takes an absolute path/relative path of your image file as an argument and returns its corresponding image matrix.
它以图像文件的绝对路径/相对路径作为参数,并返回其对应的图像矩阵。
imshow():
imshow():
It takes the window name and image matrix as an argument in order to display an image in the display window with a specified window name.
它以窗口名称和图像矩阵为参数,以便在具有指定窗口名称的显示窗口中显示图像。
cv2.cvtcolor():
cv2.cvtcolor():
It takes image matrix and a flag for changing color-space from one color space to another(in this case we are using BGR2GRAY color-space conversion) and returns the newly converted image matrix.
它需要图像矩阵和用于将颜色空间从一种颜色空间更改为另一种颜色的标志(在这种情况下,我们使用BGR2GRAY颜色空间转换),并返回新转换的图像矩阵。
Imwrite() :
Imwrite():
It takes an absolute path/relative path (of the desired location where you want to save a modified image) and image matrix as an argument.
它采用绝对路径/相对路径(要保存修改后图像的所需位置)和图像矩阵作为参数。
使用OpenCV python模块读取图像并将其另存为灰度系统的Python代码 (Python code to read an image and save it as grayscale system using OpenCV python module)
# open-cv library is installed as cv2 in python
# import cv2 library into this program
import cv2
# read an image using imread() function of cv2
# we have to pass only the path of the image
img = cv2.imread(r'C:/Users/user/Desktop/pic6.jpg')
# displaying the image using imshow() function of cv2
# In this : 1st argument is name of the frame
# 2nd argument is the image matrix
cv2.imshow('original image',img)
# converting the colourfull image into grayscale image
# using cv2.COLOR_BGR2GRAY argument of
# the cvtColor() function of cv2
# in this :
# ist argument is the image matrix
# 2nd argument is the attribute
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# save the image at specified location
cv2.imwrite(r"image\gray_img.jpg",gray_img)
Output
输出量
翻译自: https://www.includehelp.com/python/read-an-image-and-save-it-as-grayscale-system-using-opencv-python-module.aspx