大佬教程收集整理的这篇文章主要介绍了如何仅使用 Python PIL 检查 jpeg 图像是彩色还是灰度? (不使用 OpenCV),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我发现 this method 真的很有帮助,而且它实际上工作得非常准确。但是这使用 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,b=img.split()
### getTing differences between (b,g),(r,(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,r=cv2.split(img)
改为 r,b=img.split()
我知道 PIL 中存在 split()
方法。但我遇到了这个错误。
AttributeError: 'PixelAccess' object has no attribute 'split'
我该如何解决这个问题? 提前谢谢你!!
你在混合 data types
就像你是 mixing Red Bull and Vodka。
load
方法会产生错误,因为它将 PIL
图像转换为 PixelAccess
对象,您需要 PIL
的 split()
图像。此外,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,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,(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 @R_473_10586@l pixels on image:
@R_473_10586@lPixels = width * height
### finding ratio of diff_sum with respect to size of image
ratio = diff_sum/@R_473_10586@lPixels
print("Ratio is: "+ratio)
if ratio>0.005:
print("image is color")
else:
print("image is greyscale")
让我们看看 Lena 的彩色和灰度图像:
Color Lena 返回:
Ratio is: 2.981109619140625
image is color
灰度 Lena 返回:
Ratio is: 0.0
image is greyscale
以上是大佬教程为你收集整理的如何仅使用 Python PIL 检查 jpeg 图像是彩色还是灰度? (不使用 OpenCV)全部内容,希望文章能够帮你解决如何仅使用 Python PIL 检查 jpeg 图像是彩色还是灰度? (不使用 OpenCV)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。