Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 497
Harini Subhakar Avatar asked Mar 11 '15 08:03

Harini Subhakar


People also ask

How do I get the pixel value of an image in OpenCV?

Figure 5: In OpenCV, pixels are accessed by their (x, y)-coordinates. The origin, (0, 0), is located at the top-left of the image. OpenCV images are zero-indexed, where the x-values go left-to-right (column number) and y-values go top-to-bottom (row number). Here, we have the letter “I” on a piece of graph paper.


2 Answers

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)

like image 61
RMS Avatar answered Sep 19 '22 07:09

RMS


Access specific pixel in Python

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

output: [ 73 89 102]

like image 27
Rohit Salunke Avatar answered Sep 20 '22 07:09

Rohit Salunke