简体   繁体   English

如何使用 OpenCV-Python 访问图像的像素?

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

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.请提出一种方法。

I don't see what's the purpose of your x variable.我不明白你的 x 变量的目的是什么。 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() .如果要修改像素的值,请使用img.itemset() http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_core/py_basic_ops/py_basic_ops.html 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)如果要打印整个数组,请使用print(img)

Access specific pixel in Python在 Python 中访问特定像素

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

output: [ 73 89 102]输出: [ 73 89 102]

Accessing using array index will be slow with a numpy array.使用数组索引访问 numpy 数组会很慢。

You can use the item() method for access and itemset for performing changes.您可以使用item()方法进行访问,使用itemset进行更改。

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
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")

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

This code will give you the pixel values in an array 'k' by going through loop.此代码将通过循环为您提供数组“k”中的像素值。

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

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

    }
}

The vertical array are the RGB (Reg, Green, Blue) channel values for the image.垂直阵列是图像的 RGB(Reg、Green、Blue)通道值。 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文档中显示了一些基本操作

    import cv2
    import numpy as np 

    image = cv2.imread('C:/Users/Asus/Desktop/test.jpg', cv2.IMREAD_COLOR)

    for x in range (1,480):
        for y in range (1,640):

            pixel = image[x,y]
            print pixel

you are reading image in gray scale你正在阅读灰度图像

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

here you will only get intencity在这里你只会得到强度

Best way to extract image pixel (r,g,b) value is by using numpy.ndindex():提取图像像素 (r,g,b) 值的最佳方法是使用 numpy.ndindex():

  • Which will take h,w or h,w,c (height, width, channel) of an image to traverse这将采用图像的 h,w 或 h,w,c(高度、宽度、通道)来遍历

For example, code snippet is below and np.ndindex is only using height and width:例如,下面的代码片段和 np.ndindex 仅使用高度和宽度:

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:现在输出将是 r,g,b 值,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM