gpt4 book ai didi

python - 从 Python 中的图像中减去 RGB 值

转载 作者:太空宇宙 更新时间:2023-11-03 14:04:44 25 4
gpt4 key购买 nike

我在一个项目中工作,我需要从图像中减去 RGB 值。在示例中,我想从 RED 中减去 BLUE channel ,因此 RED 得到减法的差值。

我有图像的下一个属性:
尺寸: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 )

import cv2
import numpy as np
from PIL import Image

# read image into matrix.
m = cv2.imread("ITESO.jpeg")


# 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):
#m[py][px][2] = 2
n = m[py][px][2] //n takes the value of RED
Y = [n, 0, 0] //I create an array with [RED, 0, 0]
m, Y = np.array(m), np.array(Y)
m = np.absolute(m - Y) //Get the matriz with the substraction


y = 1
x = 1
print (m)
print (m[x][y])

#display image
#cv2.imshow('matrix', m)
#cv2.waitKey(0)
cv2.imwrite('new.jpeg',m)
img = Image.open('new.jpeg')
img.show()

img = Image.open('new.jpeg').convert('L')
img.save('new_gray_scale.jpg')
img.show()

当我打印 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 channel 设置为一个值,它会显示图像。我为此使用了下一行:

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 channel 相互减去?

PS:在 MatLab 中它就像一个魅力,但我无法在 python 中做到这一点。

最佳答案

请注意,此操作正在将矩阵(图像)的dtypeuint8更改为int32,这可能会导致其他problems .一个更好的方法(也更有效)来做到这一点,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()

关于python - 从 Python 中的图像中减去 RGB 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44991209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com