OpenCV 3 Computer Vision with Python Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

For this recipe, you need to perform the following steps:

  1. You can easily read an image with the cv2.imread function, which takes path to image and optional flags:
import argparse import cv2 parser = argparse.ArgumentParser() parser.add_argument('--path', default='../data/Lena.png', help='Image path.') params = parser.parse_args() img = cv2.imread(params.path)
  1. Sometimes it's useful to check whether the image was successfully loaded or not:
assert img is not None  # check if the image was successfully loaded
print('read {}'.format(params.path))
print('shape:', img.shape)
print('dtype:', img.dtype)
  1. Load the image and convert it to grayscale, even if it had many color channels originally:
img = cv2.imread(params.path, cv2.IMREAD_GRAYSCALE)
assert img is not None print('read {} as grayscale'.format(params.path)) print('shape:', img.shape) print('dtype:', img.dtype)