python判断灰度图

https://blog.csdn.net/binbin_sun/article/details/80765425

方法1比较准

import time

import cv2
import numpy as np
import os

def checkGray(chip):
    # chip_gray = cv2.cvtColor(chip,cv2.COLOR_BGR2GRAY)
    r,g,b = cv2.split(chip)
    r = r.astype(np.float32)
    g = g.astype(np.float32)
    b = b.astype(np.float32)
    s_w, s_h = r.shape[:2]
    x = (r+b+g)/3

    area_s=s_w * s_h
    # x = chip_gray
    r_gray = abs(r-x)
    g_gray = abs(g-x)
    b_gray=  abs(b-x)
    r_sum = np.sum(r_gray)/area_s
    g_sum = np.sum(g_gray)/area_s
    b_sum = np.sum(b_gray)/area_s
    gray_degree = (r_sum+g_sum+b_sum)/3
    if gray_degree <10:
        return True,gray_degree
    else:
        return False,gray_degree

def checkGray_hsv(chip):
    img_hsv = cv2.cvtColor(chip, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(img_hsv)
    s_w, s_h = s.shape[:2]
    s_sum = np.sum(s) / (s_w * s_h)
    if s_sum>10:
        pass
        return False,s_sum
        # print('color',s_sum)
    else:
        print('gray',s_sum)
        return True,s_sum


if __name__ == '__main__':


    path=r'faces_emore_images\001344/'

    start=time.time()
    files =os.listdir(path)

    for file in files:
        if file.endswith(".jpg"):
            img=cv2.imread(path+file)

            ret,value= checkGray(img)

            if ret:
                print(f'{value:.3f},'+path + file)

    print('time',time.time()-start)
发布了2853 篇原创文章 · 获赞 1112 · 访问量 581万+

猜你喜欢

转载自blog.csdn.net/jacke121/article/details/105595500