OpenCV  3.1.0-dev
Open Source Computer Vision
Basic Operations on Images

Goal

Learn to:

Almost all the operations in this section is mainly related to Numpy rather than OpenCV. A good knowledge of Numpy is required to write better optimized code with OpenCV.

*( Examples will be shown in Python terminal since most of them are just single line codes )*

Accessing and Modifying pixel values

Let's load a color image first:

1 >>> import cv2
2 >>> import numpy as np
3 
4 >>> img = cv2.imread('messi5.jpg')

You can access a pixel value by its row and column coordinates. For BGR image, it returns an array of Blue, Green, Red values. For grayscale image, just corresponding intensity is returned.

1 >>> px = img[100,100]
2 >>> print px
3 [157 166 200]
4 
5 # accessing only blue pixel
6 >>> blue = img[100,100,0]
7 >>> print blue
8 157

You can modify the pixel values the same way.

1 >>> img[100,100] = [255,255,255]
2 >>> print img[100,100]
3 [255 255 255]

warning

Numpy is a optimized library for fast array calculations. So simply accessing each and every pixel values and modifying it will be very slow and it is discouraged.

Note
Above mentioned method is normally used for selecting a region of array, say first 5 rows and last 3 columns like that. For individual pixel access, Numpy array methods, array.item() and array.itemset() is considered to be better. But it always returns a scalar. So if you want to access all B,G,R values, you need to call array.item() separately for all.

Better pixel accessing and editing method :

1 # accessing RED value
2 >>> img.item(10,10,2)
3 59
4 
5 # modifying RED value
6 >>> img.itemset((10,10,2),100)
7 >>> img.item(10,10,2)
8 100

Accessing Image Properties

Image properties include number of rows, columns and channels, type of image data, number of pixels etc.

Shape of image is accessed by img.shape. It returns a tuple of number of rows, columns and channels (if image is color):

1 >>> print img.shape
2 (342, 548, 3)
Note
If image is grayscale, tuple returned contains only number of rows and columns. So it is a good method to check if loaded image is grayscale or color image.

Total number of pixels is accessed by img.size:

1 >>> print img.size
2 562248

Image datatype is obtained by `img.dtype`:

1 >>> print img.dtype
2 uint8
Note
img.dtype is very important while debugging because a large number of errors in OpenCV-Python code is caused by invalid datatype.

Image ROI

Sometimes, you will have to play with certain region of images. For eye detection in images, first face detection is done all over the image and when face is obtained, we select the face region alone and search for eyes inside it instead of searching whole image. It improves accuracy (because eyes are always on faces :D ) and performance (because we search for a small area)

ROI is again obtained using Numpy indexing. Here I am selecting the ball and copying it to another region in the image:

1 >>> ball = img[280:340, 330:390]
2 >>> img[273:333, 100:160] = ball

Check the results below:

roi.jpg
image

Splitting and Merging Image Channels

Sometimes you will need to work separately on B,G,R channels of image. Then you need to split the BGR images to single planes. Or another time, you may need to join these individual channels to BGR image. You can do it simply by:

1 >>> b,g,r = cv2.split(img)
2 >>> img = cv2.merge((b,g,r))

Or

1 >>> b = img[:,:,0]

Suppose, you want to make all the red pixels to zero, you need not split like this and put it equal to zero. You can simply use Numpy indexing, and that is more faster.

1 >>> img[:,:,2] = 0

warning

cv2.split() is a costly operation (in terms of time). So do it only if you need it. Otherwise go for Numpy indexing.

Making Borders for Images (Padding)

If you want to create a border around the image, something like a photo frame, you can use cv2.copyMakeBorder() function. But it has more applications for convolution operation, zero padding etc. This function takes following arguments:

Below is a sample code demonstrating all these border types for better understanding:

1 import cv2
2 import numpy as np
3 from matplotlib import pyplot as plt
4 
5 BLUE = [255,0,0]
6 
7 img1 = cv2.imread('opencv_logo.png')
8 
9 replicate = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REPLICATE)
10 reflect = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT)
11 reflect101 = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_REFLECT_101)
12 wrap = cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_WRAP)
13 constant= cv2.copyMakeBorder(img1,10,10,10,10,cv2.BORDER_CONSTANT,value=BLUE)
14 
15 plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL')
16 plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
17 plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT')
18 plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT_101')
19 plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP')
20 plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANT')
21 
22 plt.show()

See the result below. (Image is displayed with matplotlib. So RED and BLUE planes will be interchanged):

border.jpg
image

Additional Resources

Exercises