溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何用python按照圖像灰度值統(tǒng)計(jì)并篩選圖片

發(fā)布時(shí)間:2020-07-20 09:09:57 來源:億速云 閱讀:335 作者:小豬 欄目:開發(fā)技術(shù)

小編這次要給大家分享的是如何用python按照圖像灰度值統(tǒng)計(jì)并篩選圖片,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。

我就廢話不多說了,大家還是直接看代碼吧!

import PIL.Image
import numpy
import os
import shutil
def sum_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
 for i in range(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("文件數(shù)量",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"))
 for i in range(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
  for i in range(256, 512):
   res_right += num[i]
  average_5_right += res_right/n

  if res_right > average_5_right:
    shutil.copyfile(file, rmfile)
    os.remove(file)
    count += 1
 print(average_5_right)
 print(count)

補(bǔ)充知識:python遍歷灰度圖像像素方法總結(jié)

啥也不說了,看代碼吧!

import numpy as np
import matplotlib.pyplot as plt
import cv2
import time

img = cv2.imread('lena.jpg',0)

# 以遍歷每個(gè)像素取反為例

# 方法1
t1 = time.time()
img1 = np.copy(img)
rows,cols = img1.shape[:2]
for row in range(rows):
 for col in range(cols):
  img[row,col] = 255 - img[row,col]
t2 = time.time()
print('方法1所需時(shí)間:',t2-t1)

# 方法2
t3 = time.time()
img2 = np.copy(img)
rows,cols = img2.shape[:2]
img2 = img2.reshape(rows*cols)
# print(img2)
for i in range(rows*cols):
 img2[i] = 255-img2[i]
img2 = img2.reshape(rows,cols)
# print(img2)
t4 = time.time()
print('方法2所需時(shí)間:',t4-t3)

# 方法3
t5 = time.time()
img3 = np.copy(img)
# 使用多維迭代生成器
for (x,y), pixel in np.ndenumerate(img3):
 img3[x,y] = 255-pixel
t6 = time.time()
print('方法3所需時(shí)間:',t6-t5)

測試結(jié)果:

方法1所需時(shí)間: 0.14431977272033691
方法2所需時(shí)間: 0.13863205909729004
方法3所需時(shí)間: 0.24196243286132812

看完這篇關(guān)于如何用python按照圖像灰度值統(tǒng)計(jì)并篩選圖片的文章,如果覺得文章內(nèi)容寫得不錯(cuò)的話,可以把它分享出去給更多人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI