用python按照图像灰度值统计并筛选图片的操作(PIL,shutil,os)
我就废话不多说了,大家还是直接看代码吧!
importPIL.Image
importnumpy
importos
importshutil
defsum_right(path):
img=PIL.Image.open(path)
array=numpy.array(img)
num=array.sum(axis=0)
print(type(num))
res_left=0
res_right=0
foriinrange(256,512):
res_right+=num[i]
print(res_right)
if__name__=='__main__':
dir2=r"C:\Users\Howsome\Desktop\tst"
dir1=r"C:\Users\Howsome\Desktop\AB"
names=os.listdir(dir1)
n=len(names)
print("文件数量",n)
res=0
average_5=25565356
average_25=26409377
average_5_right=10006019
#average_tmp=(average_25+average_5)//2
count=0
#show(os.path.join(dir1,"uni4F6C.png"))
foriinrange(n):
#取图片
img=PIL.Image.open(os.path.join(dir1,names[i]))
file=os.path.join(dir1,names[i])
rmfile=os.path.join(dir2,names[i])
array=numpy.array(img)
num=array.sum(axis=0)
res_right=0
foriinrange(256,512):
res_right+=num[i]
average_5_right+=res_right/n
ifres_right>average_5_right:
shutil.copyfile(file,rmfile)
os.remove(file)
count+=1
print(average_5_right)
print(count)
补充知识:python遍历灰度图像像素方法总结
啥也不说了,看代码吧!
importnumpyasnp
importmatplotlib.pyplotasplt
importcv2
importtime
img=cv2.imread('lena.jpg',0)
#以遍历每个像素取反为例
#方法1
t1=time.time()
img1=np.copy(img)
rows,cols=img1.shape[:2]
forrowinrange(rows):
forcolinrange(cols):
img[row,col]=255-img[row,col]
t2=time.time()
print('方法1所需时间:',t2-t1)
#方法2
t3=time.time()
img2=np.copy(img)
rows,cols=img2.shape[:2]
img2=img2.reshape(rows*cols)
#print(img2)
foriinrange(rows*cols):
img2[i]=255-img2[i]
img2=img2.reshape(rows,cols)
#print(img2)
t4=time.time()
print('方法2所需时间:',t4-t3)
#方法3
t5=time.time()
img3=np.copy(img)
#使用多维迭代生成器
for(x,y),pixelinnp.ndenumerate(img3):
img3[x,y]=255-pixel
t6=time.time()
print('方法3所需时间:',t6-t5)
测试结果:
方法1所需时间:0.14431977272033691 方法2所需时间:0.13863205909729004 方法3所需时间:0.24196243286132812
以上这篇用python按照图像灰度值统计并筛选图片的操作(PIL,shutil,os)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。