使用 OpenCV 时无法将图像转换为灰度 [英] Can't convert image to grayscale when using OpenCV
问题描述
我有一个透明的徽标,我想使用 OpenCV 将其转换为灰度.我正在使用以下代码
I have a transparent logo that I want to convert to grayscale using OpenCV. I am using the following code
def to_grayscale(logo):
gray = cv2.cvtColor(logo, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
canny = cv2.Canny(blur, 50, 150) # sick
return canny
这是图像变量:
brand_logo = Image.open(current_dir + '/logos/' + logo_image, 'r').convert('RGBA')
brand_logo = to_grayscale(brand_logo)
这是错误:
TypeError: Expected Ptr<cv::UMat> for argument 'src'
我尝试使用 PIL 中的 .convert('L')
但它使其 90% 透明灰色.无论如何我能解决这个问题吗?
I tried to use .convert('L')
from PIL but it makes it 90% transparent gray. Anyway I can fix this issue?
更新
def to_grayscale(logo):
OCVim = np.array(logo)
BGRim = cv2.cvtColor(OCVim, cv2.COLOR_RGB2BGR)
blurry = cv2.GaussianBlur(BGRim, (5, 5), 0)
canny = cv2.Canny(blurry, 50, 150)
PILim = Image.fromarray(canny)
return PILim
推荐答案
你不必要地混合了 OpenCV 和 PIL/Pillow 并且会混淆你自己.如果你用 PIL 打开一个图像,你会得到一个 PIL 图像
,这对 OpenCV 来说是双重没有用的,因为:
You are mixing OpenCV and PIL/Pillow unnecessarily and will confuse yourself. If you open an image with PIL, you will get a PIL Image
which is doubly no use for OpenCV because:
- OpenCV 需要
Numpy 数组
,而不是PIL Images
和 - OpenCV 使用 BGR 排序,而不是 PIL 使用的 RGB 排序.
- OpenCV expects
Numpy arrays
, notPIL Images
, and - OpenCV uses BGR ordering, not RGB ordering like PIL uses.
同样适用于保存图像.
有三种可能的解决方案:
There are three possible solutions:
- 坚持PIL
- 坚持使用 OpenCV
- 每次在两个包之间移动时都进行转换.
从PIL Image
转换为OpenCV的Numpy数组
:
OCVim = np.array(PILim)
要将OpenCV的Numpy array
转换为PIL Image
:
PILim = Image.fromarray(OCVim)
要反转颜色顺序,显然不需要灰度,请使用:
To reverse the colour ordering, not necessary with greyscale obviously, either use:
BGRim = cv2.cvtColor(RGBim, cv2.COLOR_RGB2BGR)
或使用负的 Numpy 步幅:
or use a negative Numpy stride:
BGRim = RGBim[..., ::-1]
这篇关于使用 OpenCV 时无法将图像转换为灰度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!