【问题标题】:Use OpenCV to separate the RGB image into red and green blue components and operate with these使用 OpenCV 将 RGB 图像分离为红色和绿色蓝色分量,并使用这些进行操作
【发布时间】:2019-09-19 16:21:00
【问题描述】:

我需要有关 OpenCV 和 Python 的帮助。

如何使用 OpenCV 和 Python 分离 RGB 图像的绿色、红色和蓝色分量?我还需要将这些矩阵中的每一个细分为 8x8 子矩阵以便使用它们,为此我正在考虑使用 numpy。

到目前为止,我的代码如下,但我对此感到困惑,我不确定它是否正确。

import matplotlib.pyplot as plt
import cv2
import numpy as np

img = cv2.imread("4.jpg")
b = img[:,:,0]
g = img[:,:,1]
r = img[:,:,2]

divb = np.split(b,8)  # divide b in submatrices 8x8?
divg = np.split(g,8)  # divide g in submatrices 8x8?
divr = np.split(r,8)  # divide r in submatrices 8x8?

print('blue:', b)
print('red:', g)
print('green:', r)

cv2.imshow('img',img)

【问题讨论】:

  • 嗨,丹尼,在任何人回答之前,请详细说明您目前的输出。
  • 你可能需要看看skimage.util.view_as_blockutility function

标签: python numpy opencv matplotlib


【解决方案1】:

不幸的是,没有内置的 numpy 方法将矩阵拆分为 8 x 8 子矩阵。此外,我处理此问题的主要假设是,您将填充图像,使图像的宽度和高度尺寸为 8 倍。我认为您肯定走在正确的轨道上:

img = cv2.imread("4.jpg")
b,g,r = cv2.split(img)

def sub_matrices(color_channel):
    matrices = []
    #How can you change how this loop iterates?
    #Also consider adding stopping conditions and/or additional loops for
    #excess parts of the image.
    for i in range(int(color_channel.shape[0]/8)):
        for j in range(int(color_channel.shape[1]/8)):
            matrices.append(color_channel[i*8:i*8 + 8, j*8:j*8+8])
    return matrices

#returns list of sub matrices
r_submatrices = sub_matrices(r)

代码应该是不言自明的。就像我说的那样,如果没有填充图像的尺寸以使尺寸为 8,则图像的某些部分将不在任何子矩阵中(特别是对于此代码;根据需要进行更改)。这段代码当然可以优化(查找缓存阻塞)并针对任何大小的子矩阵进行更改(我将留给您作为练习)。希望这会有所帮助。

【讨论】:

【解决方案2】:
import cv2
import matplotlib.pyplot as plt
    
img=cv2.imread("image.jpeg",1) 
    
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
R = img.copy() 
G = img.copy()
B = img.copy()

R[:,:,1] = R[:,:,2] = 0
G[:,:,0] = G[:,:,2] = 0
B[:,:,0] = B[:,:,1] = 0


fig = plt.figure(figsize=(18,18))
ax = fig.add_subplot(221)
bx = fig.add_subplot(222)
cx = fig.add_subplot(223)
dx = fig.add_subplot(224)

bx.imshow (R)
cx.imshow (G)
dx.imshow (B)
ax.imshow (img)



plt.show()

【讨论】:

    猜你喜欢
    • 2014-08-26
    • 1970-01-01
    • 2014-04-29
    • 2017-11-28
    • 1970-01-01
    • 2014-02-23
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多