- Mastering OpenCV 4 with Python
- Alberto Fernández Villán
- 259字
- 2021-07-02 12:07:16
Reading images in OpenCV
The following example, argparse_load_image.py, shows you how to load an image:
# Import the required packages
import argparse
import cv2
# We first create the ArgumentParser object
# The created object 'parser' will have the necessary information
# to parse the command-line arguments into data types.
parser = argparse.ArgumentParser()
# We add 'path_image' argument using add_argument() including a help. The type of this argument is string (by default)
parser.add_argument("path_image", help="path to input image to be displayed")
# The information about program arguments is stored in 'parser'
# Then, it is used when the parser calls parse_args().
# ArgumentParser parses arguments through the parse_args() method:
args = parser.parse_args()
# We can now load the input image from disk:
image = cv2.imread(args.path_image)
# Parse the argument and store it in a dictionary:
args = vars(parser.parse_args())
# Now, we can also load the input image from disk using args:
image2 = cv2.imread(args["path_image"])
# Show the loaded image:
cv2.imshow("loaded image", image)
cv2.imshow("loaded image2", image2)
# Wait until a key is pressed:
cv2.waitKey(0)
# Destroy all windows:
cv2.destroyAllWindows()
In this example, the required argument is path_image, which contains the path of the image we want to load. The path of the image is a string. Therefore, no type should be included in the positional argument because it is a string by default. Both args.path_image and args["path_image"] will contain the path of the image (two different ways of getting the value from the parameter), so we will use them as the parameter of the cv2.imread() function.
推薦閱讀
- C++案例趣學(xué)
- 深入理解Bootstrap
- Java 開發(fā)從入門到精通(第2版)
- Practical Internet of Things Security
- Servlet/JSP深入詳解
- Python高級(jí)編程
- Java深入解析:透析Java本質(zhì)的36個(gè)話題
- 深度強(qiáng)化學(xué)習(xí)算法與實(shí)踐:基于PyTorch的實(shí)現(xiàn)
- C語言程序設(shè)計(jì)
- Learning Apache Cassandra
- Kotlin開發(fā)教程(全2冊(cè))
- 深入解析Java編譯器:源碼剖析與實(shí)例詳解
- Node.js 6.x Blueprints
- 從零開始學(xué)算法:基于Python
- 你必須知道的.NET(第2版)