28

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.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Harini Subhakar
  • 281
  • 1
  • 3
  • 3

11 Answers11

35

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

Simply use:

img = cv2.imread('/path/to/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)

imxitiz
  • 3,920
  • 3
  • 9
  • 33
RMS
  • 1,350
  • 5
  • 18
  • 35
  • Hi, I know this has been a long time, I have a question regarding vertical set of numbers. Is it because it's grayscale that's why it's printing one individual value vertically? – Darkgenius007 Apr 13 '21 at 18:10
  • 1
    @Darkgenius007 Passing `flag=0` to `imread(..., flag)` is the `IMREAD_GRAYSCALE` flag. For color, you will want to pass `IMREAD_COLOR` which is 1, eg. `imread("img.jpg", 1)`. – jackw11111 Jul 14 '21 at 08:07
  • 1
    And use `rows,cols,_ = img.shape` instead. – jackw11111 Jul 14 '21 at 09:02
21

Access specific pixel in Python

import cv2
image = cv2.imread("sample.jpg")
pixel= image[200, 550]
print pixel

output: [ 73 89 102]

Rohit Salunke
  • 1,073
  • 1
  • 10
  • 14
6

Accessing using array index will be slow with a numpy array.

You can use the item() method for access and itemset for performing changes.

For example

for i in range(0,img.shape[0]):
    for j in range(0,img.shape[1]):
        pixel = img.item(i, j)
        print pixel
Neuron
  • 5,141
  • 5
  • 38
  • 59
Wickkiey
  • 4,446
  • 2
  • 39
  • 46
5
import cv2
import numpy as np

imagename = "capure.jpg"
img = cv2.imread(imagename, 0) # 0 params, for gray image
height, width = img.shape[:2]  # image height and width
print(img)  # all image pixels value in array
print(img[10, 10])  # one pixel value in 10,10 coordinate

for y in range(height):
    for x in range(width):
        print(img[y,x], end = "\t")
    print("\t")
Mahmut Aydın
  • 831
  • 13
  • 21
3

Try this:

import numpy as np
import Image

image = Image.open("example.png")
image_data = np.asarray(image)

for i in range(len(image_data)):
    for j in range(len(image_data[0])):
        print(image_data[i][j])  # this row prints an array of RGB color for each pixel in the image
3

Best way to extract image pixel (r,g,b) value is by using numpy.ndindex():

  • Which will take h,w or h,w,c (height, width, channel) of an image to traverse

For example, code snippet is below and np.ndindex is only using height and width:

import cv2
import numpy as np

image = cv2.imread("cat.jpg") 
for i, j in np.ndindex(image.shape[:-1]): #image.shape = (150,150)
    print(image[i,j])

Now the output will be r,g,b values, which will be as follows:

[ 54  97 231]
[ 63 105 241]
[ 67 109 245]
[ 71 115 250]
[ 79 125 255]
[ 81 130 255]
1

This code will give you the pixel values in an array 'k' by going through loop.

import cv2
import numpy as np

img = cv2.imread('sample.jpg',0)
rows,cols = img.shape
k = []
for i in range(rows):
    for j in range(cols):
        k.append(img[i,j])
print k
Anon George
  • 780
  • 1
  • 5
  • 11
1

You can do this

  for (int y = 0; y<im.rows; y++) 
    {

  for (int x = 0; x<im.cols; x++)
    {
        Vec3b color = im.at<Vec3b>(Point(x, y));
        //you can print color this has the pixel value

    }
}
Muskan Agarwal
  • 378
  • 5
  • 19
0

The vertical array are the RGB (Reg, Green, Blue) channel values for the image. If you want a single value for the pixel you may want to convert the image to grayscale first. It really depends on your application and what you want to do with the image, converting to grayscale is just one approach.

To convert to grayscale

grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Some basic operations are shown in the documentation

user3590169
  • 396
  • 2
  • 4
  • It is BGR in that order, not RGB as you say. Note, that when converting to grayscale, constant is XXX_*BGR*2GRAY – ivan_onys Feb 11 '20 at 15:01
0
import cv2
import numpy as np 

image = cv2.imread('/path/to/test.jpg', cv2.IMREAD_COLOR)

for x in range (1,480):
    for y in range (1,640):
        pixel = image[x,y]
        print(pixel)
imxitiz
  • 3,920
  • 3
  • 9
  • 33
0

you are reading image in gray scale

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

here you will only get intencity

paparoch
  • 450
  • 5
  • 10