![](/img/trans.png)
[英]How to check whether a jpeg image is color or gray scale using only Python stdlib
[英]How to check whether a jpeg image is color or grayscale using only Python PIL? (not using OpenCV)
我发现这个方法真的很有帮助,而且它实际上工作得非常准确。 但是这使用 OpenCV .. 我想使用 PIL 使用相同的方法。
使用 PIL 而不是 OpenCV 的代码:
from PIL import Image
import numpy as np
###test image
img=Image.open('')
img=img.load()
### splitting b,g,r channels
r,g,b=img.split()
### getting differences between (b,g), (r,g), (b,r) channel pixels
r_g=np.count_nonzero(abs(r-g))
r_b=np.count_nonzero(abs(r-b))
g_b=np.count_nonzero(abs(g-b))
### sum of differences
diff_sum=float(r_g+r_b+g_b)
### finding ratio of diff_sum with respect to size of image
ratio=diff_sum/img.size
if ratio>0.005:
print("image is color")
else:
print("image is greyscale")
我将cv2.imread('')
更改为Image.open('')
并添加了img=img.load()
。 我把b,g,r=cv2.split(img)
改为r,g,b=img.split()
我知道 PIL 中存在split()
方法。 但我有这个错误。
AttributeError: 'PixelAccess' object has no attribute 'split'
我该如何解决这个问题? 先感谢您!!
您正在混合data types
就像混合 Red Bull 和 Vodka 一样。 load
方法产生错误,因为它将PIL
图像转换为PixelAccess
对象,您需要一个用于split()
的PIL
图像。 此外, count_nonzero()
不起作用,因为它在NumPy
数组上运行,而您正试图在PIL
图像上调用该方法。 最后, size
返回图像的元组( width
和height
),因此您需要相应地修改代码:
from PIL import Image
import numpy as np
###test image
img=Image.open("D://opencvImages//lena512.png")
### splitting b,g,r channels
r,g,b=img.split()
### PIL to numpy conversion:
r = np.array(r)
g = np.array(g)
b = np.array(b)
### getting differences between (b,g), (r,g), (b,r) channel pixels
r_g=np.count_nonzero(abs(r-g))
r_b=np.count_nonzero(abs(r-b))
g_b=np.count_nonzero(abs(g-b))
### sum of differences
diff_sum=float(r_g+r_b+g_b)
### get image size:
width, height = img.size
### get total pixels on image:
totalPixels = width * height
### finding ratio of diff_sum with respect to size of image
ratio = diff_sum/totalPixels
print("Ratio is: "+ratio)
if ratio>0.005:
print("image is color")
else:
print("image is greyscale")
让我们以彩色和灰度查看Lena图像:
颜色莉娜返回这个:
Ratio is: 2.981109619140625
image is color
灰度莉娜返回这个:
Ratio is: 0.0
image is greyscale
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.