OpenCV imwrite() - 初学者指南

500 阅读3分钟

Python OpenCV是基于Intel在2000年开发的C++函数。在这篇文章中,详细解释了imwrite()函数是如何用来将图像保存到用户指定的目录中的。

安装OpenCV

由于OpenCV是一个第三方的库函数,它没有预装在任何Python IDE中。所以,一开始,你需要学习安装和配置OpenCV,以便把它作为一个导入包使用。

在这个例子中,我们使用Pycharm IDE来配置Open CV,因为它比其他IDE更简单。

让我们安装最新版本的PyCharmIDE。安装后,按照下面的步骤进行配置:

  • 创建一个新的项目。

  • 在该项目中制作一个Python文件(扩展名为.py)。

  • 然后进入 "文件">"设置",在左侧窗格中点击你创建的项目的名称。在下拉菜单中,你会发现一个名为Python解释器的选项。

  • Python解释器包含该项目所需的所有必要解释器。你需要找到并点击位于 "包 "栏上方的+号。 1.1, 打开CV配置

  • 点击它可以打开一个新的窗口,里面有大量的Python解释器的列表。你需要搜索 "opencv-Python",然后选择名为 "opencv-python "的那个,其他的都不要。 1.2 打开CV配置

  • 点击下面的安装包。这将在你的pycharm系统中安装opencv包以及其他必要的包(如果缺少的话),如 "pip"、"numpy "等。 1.3 打开CV的配置

使用OpenCV imwrite()工作

一旦完成了上述步骤,PyCharm IDE项目就可以使用了。现在我们来到了编码部分。

下面的内容将提供使用python OpenCV imwrite()保存图像的步骤。

1.导入OpenCV

为了开始保存图像,我们将导入我们需要的两个包:CV2、OS。

import cv2
import os

这篇文章将采用两个OpenCV函数来保存图像。这两个需要的cv2函数是:

  • imread()
  • imwrite()

2.读取一个图像

在读取图像之前,程序员需要向编译器指定文件路径和目录。

首先,变量 "imagelocation "被初始化为图像的文件路径,而另一个变量 "filedirectory "被用来保存新图像文件的目录路径。

当这两个变量都被初始化后,imread()函数被用来读取图像。

示例代码:

imagelocation = (r"C:\Users\Win 10\PycharmProjects\pythonProject\lena.jpg")

filedirectory = (r"C:\Users\Win 10\Pictures")

image = cv2.imread(imagelocation)

注意:要保存的图像文件应该存在于Python项目文件夹中。你可以使用PyCharm IDE复制图像并粘贴到该文件夹中,也可以手动搜索该文件夹并将图像粘贴到其中。

3.保存一个图像

在这里,一个新的名字被存储在变量'newfilename'中,然后函数imwrite()接收前面例子中使用的变量'image'并以新的名字保存它。

示例代码:

newfilename = 'image_savedasnew.jpg'<br><br>cv2.imwrite(newfilename, image)

4.使用OpenCV imwrite()工作的完整代码

import cv2
import os

imagelocation = (r"C:\Users\Win 10\PycharmProjects\pythonProject\lena.jpg")

filedirectory = (r"C:\Users\Win 10\Pictures")

image = cv2.imread(imagelocation)


# Reading the image
image = cv2.imread(imagelocation) 

# Using print command here is not necessary but helpful. If the filepath in both the variables ‘imagelocation’, and ‘filedirectory’  is stored successfully, this command will print a matrix of the image. If there is any mistake in filepath, the compiler will return ‘none’.

print(image)

#to direct compiler towards specified directory
os.chdir(filedirectory)        
  
# It shows the contents of the directory before file is saved 

print("list of files available before saving function is executed:")  

print(os.listdir(filedirectory))

newfilename = 'image_savedasnew.jpg'

# This is the function specified above that saves image file 
cv2.imwrite(newfilename, image)

#Lists directory contents after saving

print("Following execution of imwrite function:")  
print(os.listdir(directory))
print('Image Saved Positively')



输出

结论

至此,这个关于Python OpenCV imwrite()函数的快速而简单的教程结束。你可以在OpenCV库中探索更多的东西,我鼓励你在这里浏览我们的OpenCV教程集。