在Python中从图像中减去RGB值

2024-05-16 01:35:07 发布

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

我正在一个项目中工作,我需要从图像中减去RGB值。在例子中,我想用红色减去蓝色通道,所以红色得到减法的差值。在

我有图像的下一个属性:
尺寸:1456x2592, bpp:3个在

我使用的图像提供了以下数组:

 [[[ 63  58  60]
     [ 63  58  60]
     [ 64  59  61]
      ...,  
     [155 155 161]  
     [155 155 161] 
     [155 155 161]]

     [[ 58  53  55]
      [ 60  55  57]
      [ 62  57  59]
       ...,  
      [157 157 163]
      [157 157 163]
      [158 158 164]]

我知道这些是图像中的值(RGB),所以现在我继续做代码(我基于this code

^{pr2}$

当我打印J矩阵时,它给出了以下数组:

B、G、R

蓝色=蓝色-红色

[[[  3  58  60]
  [  3  58  60] 
  [  4  59  61]
  ...,  
 [ 95 155 161]
 [ 95 155 161] 
 [ 95 155 161]]

[[  2  53  55] 
 [  0  55  57]
 [  2  57  59]
 ...,  
 [ 97 157 163] 
 [ 97 157 163] 
 [ 98 158 164]]

但是我无法打开新图像,如果我将一个RGB通道设置为一个值,它会显示图像。我用下面几行:

import cv2
import numpy as np

# read image into matrix.
m =  cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
for py in range(0,h):
    for px in range(0,w):
        m[py][px][0] = 0 //setting channel Blue to values of 0

# display image
cv2.imshow('matrix', m)
cv2.waitKey(0) 

如何从彼此中减去RGB通道?在

PS:在MatLab中,它的工作方式很有魅力,但我不能用python来实现。在


Tags: inpy图像imageimportfornprange
2条回答

请注意,此操作将矩阵(图像)的dtypeuint8更改为{},这可能导致其他{a1}。IMO,一个更好(更有效)的方法是:

import cv2
import numpy as np

img =  cv2.imread('image.png').astype(np.float)  # BGR, float
img[:, :, 2] = np.absolute(img[:, :, 2] - img[:, :, 0])  # R = |R - B|
img = img.astype(np.uint8)  # convert back to uint8
cv2.imwrite('new-image.png', img)  # save the image
cv2.imshow('img', img)
cv2.waitKey()

代码正在将RGB负值操作为零。。。在

m =  cv2.imread("img.jpg")

# get image properties.
h,w,bpp = np.shape(m)

    # iterate over the entire image.
    # BLUE = 0, GREEN = 1, RED = 2.

    for py in range(0,h):
        for px in range(0,w):
            n = m[py][px][1]
            Y = [0, 0, n]
            m, Y = np.array(m), np.array(Y)
            a = (m - Y)
            if (a[py][px][0] <=0): #if Blue is negative or equal 0
                a[py][px][0] = 0   #Blue set to 0 
    cv2.imwrite('img_R-G.jpg',a)
    img = Image.open('img_R-G.jpg').convert('L')
    img.save('img_R-G_GS.jpg')

相关问题 更多 >