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.
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.
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)
Access specific pixel in Python
import cv2 image = cv2.imread("sample.jpg") pixel= image[200, 550] print pixel
output: [ 73 89 102]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With