灰度PIL图像为OpenCV格式 [英] PIL image in grayscale to OpenCV format

查看:337
本文介绍了灰度PIL图像为OpenCV格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里找到了与从RGB图像进行更一般转换有关的先前答案:将图像从PIL转换为openCV格式

I found the previous answer related to a more general conversion from RGB image here: Convert image from PIL to openCV format

我想知道当必须以灰度格式读取图像时的区别.

I would like to know the difference when an image has to be read as a grayscale format.

images = [None, None]

images[0] = Image.open('image1')
images[1] = Image.open('image2')

print(type(images[0]))

a = np.array(images[0])
b = np.array(images[1])

print(type(a))

im_template = cv2.imread(a, 0)
im_source = cv2.imread(b, 0)

我得到以下输出:

<class 'PIL.JpegImagePlugin.JpegImageFile'>
<class 'numpy.ndarray'>

即使我能够将图像转换为ndarray,cv2也会说:内置操作的错误参数类型".我不需要RGB到BGR的转换.传递cv2 read参数时,我还应该考虑什么?

Even though I am able to convert the image to ndarray, cv2 says: "bad argument type for built-in operation". I do not need an RGB to BGR conversion. What else should I consider while passing a cv2 read argument?

推荐答案

您使自己不必要的生活变得困难.如果要加载灰度图像,并将其与OpenCV一起使用,则应该执行以下操作:

You are making life unnecessarily difficult for yourself. If you want to load an image as greyscale, and use it with OpenCV, you should just do:

im = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

仅此而已.不需要使用PIL(速度较慢),也不需要使用cvtColor(),因为无论如何您已经浪费了所有的内存以BGR读取它.

and that's all. No need to use PIL (which is slower), no need to use cvtColor() because you have already wasted all the memory reading it in BGR anyway.

如果您绝对想使用PIL读取它(出于某种奇怪的原因),请使用:

If you absolutely want to read it using PIL (for some odd reason), use:

import numpy as np
from PIL import Image

# Read in and make greyscale
PILim = Image.open('image.jpg').convert('L')

# Make Numpy/OpenCV-compatible version
openCVim = np.array(PILim)

如果要从OpenCV/Numpy映像返回到PIL映像,请使用:

By the way, if you want to go back to a PIL image from an OpenCV/Numpy image, use:

PILim = Image.fromarray(openCVim)

这篇关于灰度PIL图像为OpenCV格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆