How do I access the pixels of an image using OpenCV-Python?

Harini Subhakar picture Harini Subhakar · Mar 11, 2015 · Viewed 86.2k times · Source

I want to know how to loop through all pixels of an image. I tried this:

import cv2
import numpy as np

x = np.random.randint(0,5,(500,500))
img = cv2.imread('D:\Project\Capture1.jpg',0)
p = img.shape
print p
rows,cols = img.shape

for i in range(rows):
    for j in range(cols):
        k = x[i,j]
        print k

It prints a vertical set of numbers which is not in the form of an array. I am also getting an array out of bounds exception. Please suggest a method.

Answer

RMS picture RMS · Sep 28, 2016

I don't see what's the purpose of your x variable. You don't need it.

Simply use:

img = cv2.imread('D:\Project\Capture1.jpg',0)
rows,cols = img.shape

    for i in range(rows):
      for j in range(cols):
         k = img[i,j]
         print k

which will print indeed a vertical set of numbers. If you want to modify the values of the pixels use img.itemset(). http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_core/py_basic_ops/py_basic_ops.html

If you want to print the whole array then use print(img)