Monday 19 January 2015

Convert RGB to gray / other color spaces

Convert RGB to gray / other color spaces



cv2.cvtColor(src, code[, dst[, dstCn]]) → dst

Parameters:
  • src – input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision floating-point.
  • dst – output image of the same size and depth as src.
  • code – color space conversion code (see the description below).
  • dstCn – number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code .
This function converts one image from one colorspace to another.The default color format in openCV is RGB.But is is actually BGR(byte reversed).so in an 24 bit color image the first 8 bits are blue components,2nd byte is green and third one is red.

The conventional ranges for R, G, and B channel values are:
  • 0 to 255 for CV_8U images
  • 0 to 65535 for CV_16U images
  • 0 to 1 for CV_32F images

Example:

Converting to grayscale:

Steps:

  1. Load an image 
  2. Convert to gray scale
  3. Show result
Code:

------------------------------------------

import cv2

# Load a color image
img = cv2.imread('image1.jpg',1)

#convert RGB image to Gray
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#Display the color image
cv2.imshow('color_image',img)

#Display the gray image
cv2.imshow('gray_image',gray)

cv2.waitKey(0)
cv2.destroyAllWindows()


-------------------------------------------