OpenCV+Python:Part 2–Working with Images

–Access and Edit Pixel Values

All of the following steps can be performed using the Python terminal.
First of all load the image:

>>>import cv2
>>>import numpy as np
>>>img = cv2.imread('image.jpg')

To get a pixel value of a particular position:

>>>pix = img[x,y] #x,y are the coordinates
>>>print pix

To modify the pixel value of a particular point (x,y)

>>>img[x,y]=[B,G,R] #where B,G,R are integer values

A much faster method is using Numpy functions array.item() and array.itemset() to access and edit pixel values.However it only returns a scalar value.So to access the B,G,R values you need call the function array.item() separately for all.

–Image Properties
1.)>>>print image.shape
Its returns the a tuple with number of rows,columns and channels.
2.)>>>print image.size
Returns the numbers of pixels accessed by the image.
3.)>>>print img.dtype
Returns the Image datatype.

To select a particular region of image:
>>>part = img[x1:y1,x2:y2]

To paste the selected ROI at some other location:
>>>img[p1:q1,p2:q2] = part

–Splitting and Merging Channels

If you want to split B,G,R channels or merge them back use:

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

However if you want to edit a particular channel a faster method would be to use numpy.
E.g. to set all red pixels to zero:

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

Thats all in this post..

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s