Basic Image Processing with OpenCV, NumPy and Matplotlib (1)

In this post I want to use simple OpenCV functions for image processing, we’ll show different concepts and its corresponding example. For this examples we use the image shown below:

Astronomic picture of the day. By NASA
Astronomic picture of the day. By NASA

Histograms are a basic tool in image processing. They are frequency distributions, therefore histograms of images describe the frequency of the intensity values that occur in an image.

A histogram is used to put up image statistics in an easily interpreted visual format. We can use a histograms of images to:

  • Discover problems in an image
  • Improve the visual appearance of an image
  • As a forensic tool for determininig what type of processing has previously been applied to an image

To create a histogram I used OpenCV, NumPy and Matplotlib. This is my script.

import matplotlib.pyplot as pyplt
import numpy as np
import cv

src = cv.LoadImageM(sys.argv[1])
size = 256
histo = np.zeros(size, dtype = np.int32)

for x in range(0, src.height):
  for y in range(0, src.width):
    tuple = cv.Get2D(src, x, y)
    histo[(tuple[0] + tuple[1] + tuple[2])/3] += 1 = np.arange(histo.size), height = histo)

We load an image (4) and save it in an Iplimage object. We define the array size (5) and we create a numpy array with this value(6). After this, we map the array RGB values, we obtain its average, and add a unit to the corresponding index in the array 8-11. Finally, we show the histogram 13-14.

Histogram of RGB image
Histogram of RGB image

However, we can improve a little bit the effectiveness of this script if we compute a grayscale image. We only need add two lines:

cpy = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_8U, 1)
cv.CvtColor(src, cpy, cv.CV_RGB2GRAY)
Histogram of grayscale image
Histogram of grayscale image

The runtime decreases approximately in ten seconds, although both histograms show a similar pixel frequency distribution. In the next post I’ll show basic filters in image processing and its implementation with OpenCV.


5 comentarios sobre “Basic Image Processing with OpenCV, NumPy and Matplotlib (1)


Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )


Conectando a %s