python灰度图像为什么显示成彩色的_使用Python / PIL检测图像是彩色,灰度还是黑白...

I extract pages images from a PDF file in jpeg format and I need to determine if each image is much more grayscale, color ou black and white (with a tolerance factor).

I have found some ways to work with color detection with PIL ( here and here ) but I can't figure out how to answer this simple (visual) question : is it much more black and white, color or grayscale image ?

I prefer working with Python and PIL for this part but I could use too OpenCV if someone has a clue (or solution).

解决方案

I tried Gepeto's solution and it has a lot of false positives since the color grand variances can be similar just by chance. The correct way to do this is to calculate the variance per pixel. Shrink down the image first so you don't have to process millions of pixels.

By default this function also uses a mean color bias adjustment, which I find improves the prediction. A side effect of this is that it will also detect monochrome but non-grayscale images (typically sepia-toned stuff, the model seems to break down a little in detecting larger deviations from grayscale). You can separate these out from true grayscale by thresholding on the color band means.

I ran this on a test set of 13,000 photographic images and got classification with 99.1% precision and 92.5% recall. Accuracy could probably be further improved by using a nonlinear bias adjustment (color values must be between 0 and 255 for example). Maybe looking at median squared error instead of MSE would better allow e.g. grayscale images with small color stamps.

from PIL import Image, ImageStat

def detect_color_image(file, thumb_size=40, MSE_cutoff=22, adjust_color_bias=True):

pil_img = Image.open(file)

bands = pil_img.getbands()

if bands == ('R','G','B') or bands== ('R','G','B','A'):

thumb = pil_img.resize((thumb_size,thumb_size))

SSE, bias = 0, [0,0,0]

if adjust_color_bias:

bias = ImageStat.Stat(thumb).mean[:3]

bias = [b - sum(bias)/3 for b in bias ]

for pixel in thumb.getdata():

mu = sum(pixel)/3

SSE += sum((pixel[i] - mu - bias[i])*(pixel[i] - mu - bias[i]) for i in [0,1,2])

MSE = float(SSE)/(thumb_size*thumb_size)

if MSE <= MSE_cutoff:

print "grayscale\t",

else:

print "Color\t\t\t",

print "( MSE=",MSE,")"

elif len(bands)==1:

print "Black and white", bands

else:

print "Don't know...", bands

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值