Using OpenCV – Convert Image to Gray Scale in .

In the past posts we looked at doing some image conversions using arrays and manual steps.

All that is fun, it lets us see what is going on inside the black box. However, deadlines and everything else – we don’t want to have to reinvent the wheel each time.

Thankfully there is a powerful image library out there called – OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library.

The library has more than 2500 optimized algorithms, which includes a comprehensive set of both classic and state-of-the-art computer vision and machine learning algorithms.

Now, try creating that – debugging etc. Sometimes it is better to stand on the shoulders of a gaint and see farther then they can.

Here is our first thing – convert an image to gray scale. Make sure you have installed OpenCV for Python.

#%%
import cv2

# Image File we are loading
imageFile = r"D:\temp\thecats.jpg"

# Have open CV2 read the image file - Something to note cv2.imread decodes the image file into BGR - Blue Green Red, instead of RGB
inputImage = cv2.imread(imageFile)

# Convert the image to gray scale - Does an average from the color channels.
grayImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)

# Display the gray scale image. Until key press
cv2.imshow("Image File", grayImage)
cv2.waitKey(0)
cv2.destroyAllWindows()

Want an even easier way? How about having OpenCV do it when it reads the image in.

import cv2

# Image File we are loading
imageFile = r"D:\temp\thecats.jpg"

# Have open CV2 read the image file - Converts to Gray scale on read
inputImage = cv2.imread(imageFile,cv2.IMREAD_GRAYSCALE)

cv2.imshow("Image File", inputImage)

cv2.waitKey(0)
cv2.destroyAllWindows()

See the Image Processing Table of Contents



Have a Project or Idea!?

Seeking Bespoke Technology Solutions?

jamie@jamiestarling.com


Pin It on Pinterest

Share This