Python | cv2 imwrite()方法
时间:2020-02-23 14:42:15 来源:igfitidea点击:
在本教程中,我们将通过使用作为CV2(计算机视觉)库存在的Open-CV,使用Python了解如何使用Python在我们自己的系统中保存图像。
我们可以使用 imwrite()
的方法 cv2
库在系统上保存图像。
要使用CV2库,我们需要使用CV2库使用 import statement
。
现在让我们看看语法和返回值 imwrite()
方法,然后我们将继续执行以下示例。
语法
cv2.imwrite(path, image)
参数
我们需要将两个参数传递给imwrite()方法。
参数是:
path:
我们想要以包含文件名的字符串形式在系统中保存图像的位置地址。
其中这两个案例是可能的:i)
如果要在当前工作目录中保存图像,那么我们只需提到其扩展名的图像的名称.jpg
那.png
等,ii)
如果要在系统中的其他位置保存图像,则不在当前工作目录中,我们必须提供完整的路径,也称为图像的绝对路径。image:
它是该图像的图像像素矩阵,我们要在系统中保存。
返回值
它返回true或者false。
返回 True
如果图像已成功保存,否则返回 False
。
cv2 imwrite()方法示例
现在让我们看看Python代码:
# import computer vision library(cv2) in this Program import cv2 # import os library in this program import os # main code if __name__ == "__main__" : # mentioning absolute path of the image img_path = "C:\Users\user\Desktop\flower.jpg" # read an image image = cv2.imread(img_path) print("Before saving an image ,contents of directory shows :") # shows the contents of given directory print(os.listdir("C:\Users\user\Desktop\save image")) # mentioning absolute path save_img_path = "C:\Users\user\Desktop\save image\image1.jpg" # save an image at the given mention path cv2.imwrite(save_img_path,image) print("After saving an image ,contents of directory shows :") # shows the contents of given directory print(os.listdir("C:\Users\user\Desktop\save image"))
输出 :
Before saving an image, contents of directory shows : [] After saving an image, contents of directory shows : ['image1.jpg']