如何在 Python 中用 opencv 访问图像的 B、G、R?

How to acces to the B,G,R of an image with opencv in Python?

我想访问图像的所有 R、G、B 通道,我写了一些代码,但它只给了我一个像素的 R、G、B,即使我做了附加...

我是 Python 的初学者,你能帮帮我吗?

代码如下:

#coding: utf8
import numpy as np
import cv2
from imageio import imread

imgcolor = imread("/home/PATH/bougieHaut3.jpg")
rows,cols,rgb = imgcolor.shape
for i in range(rows):
    for j in range (cols):
        blue = imgcolor[i,j,0]
        B=[]
        B.append(blue)
        green = imgcolor[i,j,1]
        G=[]
        G.append(green)
        red = imgcolor[i,j,2]
        R=[]
        R.append(red)
print(B,G,R)

非常感谢您的帮助:)!

您正在为每个像素重新创建 R/G/B 列表,因此它们最终将只包含一个条目。

尝试

import numpy as np
import cv2
from imageio import imread

imgcolor = imread("/home/PATH/bougieHaut3.jpg")
rows, cols, rgb = imgcolor.shape
R = []
G = []
B = []
for i in range(rows):
    for j in range(cols):
        B.append(imgcolor[i, j, 0])
        G.append(imgcolor[i, j, 1])
        R.append(imgcolor[i, j, 2])
print(B, G, R)

编辑:使用 Numpy 切片的更快方法是

imgcolor = imread("/home/PATH/bougieHaut3.jpg")
B = imgcolor[:,:,0].flatten()
G = imgcolor[:,:,1].flatten()
R = imgcolor[:,:,2].flatten()

没有循环 – 如果需要,您可以使用 list() 将这些 Numpy 数组转换为列表。

您可以定义不变函数,例如: 进口太平船 导入数学

def invariant_r(img):
  c1 = np.zeros((img_height, img_weight))
  for i in range(0, img_height):
    for j in range(0, img_weight):
      b = img[i,j,0]
      g = img[i,j,1]
      r = img[i,j,2]
      x = (r/max(g,b))
      c1[i][j]= math.atan(x)
  return c1

def invariant_g(img):
  c1 = np.zeros((img_height, img_weight))
  for i in range(0, img_height):
    for j in range(0, img_weight):
      b = img[i,j,0]
      g = img[i,j,1]
      r = img[i,j,2]
      x = (g/max(r,b))
      c1[i][j]= math.atan(x)
  return c1

def invariant_b(img):
  c1 = np.zeros((img_height, img_weight))
  for i in range(0, img_height):
    for j in range(0, img_weight):
      b = img[i,j,0]
      g = img[i,j,1]
      r = img[i,j,2]
      x = (b/max(r,g))
      c1[i][j]= math.atan(x)
  return c1

并这样称呼他们:

 r_img = invariant_r(img)
  g_img = invariant_g(img)
  b_img = invariant_b(img)

将这些值合并到一个数组中后,您就得到了颜色不变数组。