# -*- coding: utf-8 -*-
from PIL import Image
import matplotlib.pyplot as plt
import cv2
import time
import numpy as np
import cv2 as cv
def iscolor(url):
print(‘---iscolor‘)
colortype = ‘‘
start = time.perf_counter()
image = cv2.imread(url)
if(image.shape[2]==1):
colortype= ‘Gray Image‘
elif(image.shape[2] == 3):
colortype=(‘Color Image‘)
else:
colortype=(‘error‘)
end = time.perf_counter()
print(end - start)
return colortype
def is_color_image(url):
print(‘---is_color_image‘)
start = time.perf_counter()
im=Image.open(url)
pix=im.convert(‘RGB‘)
width=im.size[0]
height=im.size[1]
oimage_color_type=‘Gray Image‘
is_color=[]
for x in range(width):
for y in range(height):
r,g,b=pix.getpixel((x,y))
r=int(r)
g=int(g)
b=int(b)
if (r==g) and (g==b):
pass
else:
oimage_color_type=‘Color Image‘
end = time.perf_counter()
print(end - start)
return oimage_color_type
# 判断黑白图片或彩色图片
def compare_color_or_gray(image_path):
print(‘---compare_color_or_gray‘)
start =time.perf_counter() # time.clock()
image = cv.imread(image_path)
b_hist = cv.calcHist([image], [0], None, [256], [0, 256])
g_hist = cv.calcHist([image], [1], None, [256], [0, 256])
r_hist = cv.calcHist([image], [2], None, [256], [0, 256])
b_2_g = cv.compareHist(b_hist, g_hist, cv.HISTCMP_CORREL)
g_2_r = cv.compareHist(g_hist, r_hist, cv.HISTCMP_CORREL)
r_2_b = cv.compareHist(r_hist, b_hist, cv.HISTCMP_CORREL)
CORREL_ABS = np.abs(b_2_g - g_2_r) + \
np.abs(g_2_r - r_2_b) + \
np.abs(r_2_b - b_2_g)
end = time.perf_counter()
if CORREL_ABS < 0.09: # 黑白彩色图像的直方图很相似
colortype= ‘Gray Image‘
else:
colortype= ‘Color Image‘
print(end - start)
return colortype
if __name__ == ‘__main__‘:
url=‘D:/AI.IMG/a1.jpg‘
print(url, iscolor(url)) # 该方法不准确
print(url, is_color_image(url)) # 可以判断,但是用时较长 约2.4秒
print(url, compare_color_or_gray(url)) # 可以判断,用时0.03秒