前言
图像脏污检测,可利用亮度差和卷积神经网络等检测方法。
一、Blemish check
将图像分块检测每块与周围的亮度差.
图像均值、方差、标准差 :
均值(mean) = (a0, a1…an-1) / n
方差= ((a0 - mean)² + (a1 - mean)² +…+ (an-1 - mean)²) / n
标准差 = 方差开方
标准差反映了图像像素值与均值的离散程度。
二、检测步骤
1.引入库
from PIL import Image, ImageStat
import cv2
import numpy as np
import matplotlib.pyplot as plt
2.检测图像
代码如下:
class blemish(object):
'''
This module is for blemish check:
Global blemish check
Regional blemish check
'''
def __init__(self):
print('\n******blemish check******')
def Regional_blemish(self):
'''
Regional blemish check:
1,divide image into M*N blocks;
2,get average luminance and standard deviation of each block. If Std>0.5*Average, mark the block as "NG".
3,check each block. Skip the "NG" block. Get the max delta between a block with its adjacent 8 blocks.
4,Get the max delta.
'''
#img = Image.open('blemish.png')
width, height = img.size
# block size
block_size_w = int(width/16)#64
block_size_h = int(height/12)#48
list_mean=[]# get luminance of each block
list_std=[]
for x in range(0, width, block_size_w):
for y in range(0, height, block_size_h):
x1 = x
y1 = y
x2 = x + block_size_w
y2 = y + block_size_h
# get block
block = img.crop((x1, y1, x2, y2))
# save block
block.save('{}_{}_{}.jpg'.format(x1, y1, block_size_w))
# get the mean and std
blocks=block.convert('L')#
blocks=blocks.getdata()
blocks=np.array(blocks)
print('Block average luminance and standard deviation: %.2f ,%.2f'%(blocks.mean(0),blocks.std(0)))
list_mean.append(blocks.mean(0))
list_std.append(blocks.std(0))
if blocks.std(0)>0.5 * blocks.mean(0):
print('\tThe %d_%d block is NG,Skip.\n'%(x1,y1))
else:
#Get the delta
delta=[]
# 4 Neighborhood or 8 neighborhood
coordinate=[(x1-block_size_w,y1,x2-block_size_w, y2),(x1,y1-block_size_h,x2, y2-block_size_h),(x1+block_size_w,y1,x2+block_size_w, y2),(x1,y1+block_size_h,x2, y2+block_size_h)]
for i in coordinate:
block_1= img.crop(i)
block_1=block_1.convert('L').getdata()
block_1=np.array(block_1)
delta_3=blocks.mean(0)-block_1.mean(0)
delta.append(delta_3)
print('The delta of the 4 neighborhood:%s'%delta)
deltal_2=max(delta)# get the max value among them
print('The max delta: %.2f'%deltal_2)
threshold_2=10
if deltal_2>threshold_2:
print('\nWarning "Blemish Detected!\n"')
else:
print('\nGoto OTP write\n')
pass
原始图片:
有脏污的块:
Block average luminance and standard deviation: 2.89 ,26.98
The 80_0 block is NG,Skip.
Block average luminance and standard deviation: 31.75 ,84.20
The 80_53 block is NG,Skip.
Block average luminance and standard deviation: 0.84 ,14.63
The 120_0 block is NG,Skip.
Block average luminance and standard deviation: 9.26 ,47.71
The 120_53 block is NG,Skip.
总结
本文利用图像均值和标准差检测白色脏污,作简单展示,完整的脏污检测算法有待进一步训练。