【问题标题】:Pillow equivalent of the following openCV codePillow 等效于以下 openCV 代码
【发布时间】:2019-08-20 17:57:27
【问题描述】:

我正在尝试将以下用 openCV 编写的代码模块转换为枕头,但我不知道该怎么做? j 是 rgb 图像

img = cv2.imread(j,1)
b,g,r = cv2.split(img)
green = 2*g-r-b

在这里,我正在读取彩色图像,然后拆分为通道,然后在绿色通道上执行转换,然后进一步使用绿色通道进行进一步操作,但我无法计算出与上述代码等效的枕头。 我试过这个问题Python PIL image split to RGB,但我无法得到2*g-r-b的结果

【问题讨论】:

标签: python-3.x opencv python-imaging-library


【解决方案1】:

您可以像这样使用 PIL 和 Numpy 来做到这一点 - 我倾向于使用 Numpy,因为它更快、更灵活:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Open input image and ensure it is RGB
im = Image.open('start.png').convert('RGB')

# Make into Numpy array
imnp = np.array(im)

# Split into 3 constituent bands
r = imnp[:, :, 0]
g = imnp[:, :, 1]
b = imnp[:, :, 2]

# Process
g = 2*g - r - b

# Recombine to single image and save
merged = np.dstack((r, g, b))
Image.fromarray(merged).save('result.png')

或者您可以不那么明确地拆分并在整个图像上就地执行:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Open input image and ensure it is RGB
im = Image.open('start.png').convert('RGB')

# Make into Numpy array
imnp = np.array(im)

# Process
imnp[:,:,1] = 2*imnp[:,:,1] - imnp[:,:,0] - imnp[:,:,2]

# Save
Image.fromarray(imnp).save('result2.png')

关键字:Python、Numpy、PIL、Pillow、颜色矩阵、颜色矩阵、变换、乘通道、缩放通道、分离、单独、单个通道、波段、组件、单独、图像、图像处理。

【讨论】:

  • 是的,它解决了我的问题,但是有什么方法可以让我不必每次都保存图像,并且可以使用特定的颜色通道波段进行进一步处理。因为在 openCV 中,我可以使用单独的波段(在这种情况下假设为绿色)并且可以对其执行操作而无需保存任何内容
  • 当然。你不必保存任何东西。我只是出于礼貌展示了如何重新组合频道,因为我将它们分开并猜测您可能想要重新组合它们,但您不必这样做。另请注意,我使用的 Numpy 数组(imnprgb)完全相同,并且可以与您的 OpenCV imgbg 和 @987654330 完全互换@。您可以将我的数组与您的 OpenCV 代码一起使用,或者将您的 OpenCV 数组与我的 Numpy/PiIL 代码一起使用!
  • 是的,我明白了。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 2011-04-18
  • 2021-11-04
  • 2011-12-01
  • 2016-03-05
  • 1970-01-01
相关资源
最近更新 更多