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) ...

Get OpenCV 3 Computer Vision with Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.