OpenCV_python3_01

Practical Python and OpenCV,3rd Edition 01


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格式的图像,第一个参数是我们要保存的图像的路径名,第二个是我们希望保存的图像。

最后执行脚本程序:

显示效果图片

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

完整的代码

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)

用到的函数

imread

imshow

waitKey

imwrite

danger no-icon

在上面的代码中,height对应于shape[0],width对应于shape[1]。也就是Numpy 的shape似乎和自己想的不一样(specifying the height before the width)。但是,就matrix definition而言,这实际上是有意义。因为当我们定义矩阵的时候,我们通常将它们写成(# of rows x # of columns)的形式。这里,我们的图片有height:400 pixels(the number of rows) 以及 width:400 pixels(the number of columns).

更多的参考:

loading-displaying-and-saving

How-To: OpenCV Load an Image

Python Command Line Arguments

How to Display a Matplotlib RGB Image

Resolved: Matplotlib figures not showing up or displaying


---------------- The End ----------------
支持一下
Fork me on GitHub ;