使用OpenCV将RGB图像分为红、绿、蓝两部分,并使用

2024-10-06 10:22:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要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)

Tags: in图像importnumpyimgasnp矩阵
1条回答
网友
1楼 · 发布于 2024-10-06 10:22:45

不幸的是,没有内置的numpy方法将矩阵拆分为8乘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的维度,那么图像的部分就不会在任何子矩阵中(对于这个代码,具体来说,不管你需要什么,都要修改它)。这段代码当然可以优化(查找缓存块)和修改任何大小的子矩阵(我将留给您作为练习)。希望这有帮助。你知道吗

相关问题 更多 >