opencv加载,显示以及保存图片

load、display、save

from __future__ import print_function
import argparse
import cv2

解释

future package中导入print_function,是因为我们将使用实际的print() function,而不是print statement,这样我们的代码就可以在python2.7以及python3中共同运行。

ap = argparse.ArgumentParser()
ap.add_argument('-i',"--image",required=True,
help="Path to the image")
args = vars(ap.parse_args())

解释

使用“--image”参数,也就是我们图像在磁盘的路径,我们将这个路径进行parse,然后将他们存储在一个字典中。

image = cv2.imread(args["image"])
print("height: {} pixels".format(image.shape[0]))
print("width : {} pixels".format(image.shape[1]))
print("channels : {}".format(image.shape[2]))
cv2.imshow("Image",image)
cv2.waitKey(0)

解释

cv2.imread函数将返回一个Numpy数据,代表着图像。对于Numpy数组,我们可以使用shape属性来获取图像的width、height以及channels的数量。imshow函数将我们的图像显示在Windows窗口中,它的第一个参数是"name" of our window.第二个参数是我们从磁盘加载的图像了。而waitKey函数会暂停我们的脚本程序,直到我们在键盘上按下一个key之后才继续执行,而参数0则表示我们按键盘上的任意键都可以继续执行脚本程序。

cv2.imwrite("newimage.jpg",image)

解释

最后我们使用imwrite函数将我们的保存为jpg格式的图像,第一个参数是我们要保存的图像的路径名,第二个是我们希望保存的图像。

最后执行脚本程序:

opencv加载,显示以及保存图片

显示效果图片

opencv加载,显示以及保存图片

停止脚本程序很简单,就如前面所说的,在显示的图片的任意地方按键盘上的任意键即可。然后查看脚本目录,你可以看到一个newimage.jpg的图片

opencv加载,显示以及保存图片

完整的代码

from __future__ import print_function
import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument('-i',"--image",required=True,
help="Path to the image")

args = vars(ap.parse_args())
image = cv2.imread(args["image"])
print("height: {} pixels".format(image.shape[0]))
print("width : {} pixels".format(image.shape[1]))
print("channels : {}".format(image.shape[2]))
cv2.imshow("Image",image)
cv2.waitKey(0)
cv2.imwrite("newimage.jpg",image)

更多请参考我的博客:https://0leo0.github.io/2018/OpenCV_python3.html


分享到:


相關文章: