#!/usr/bin/env python 
# coding=utf-8
#1.编译器声明和2.编码格式声明
#1:为了防止用户没有将python安装在默认的/usr/bin目录，系统会先从env(系统环境变量)里查找python的安装路径，再调用对应路径下的解析器完成操作，也可以指定python3
#2:Python.X 源码文件默认使用utf-8编码，可以正常解析中文，一般而言，都会声明为utf-8编码

import cv2 #引用OpenCV功能包

import numpy as np #引用数组功能包
import matplotlib.pyplot as plt
import pygal

#读取图片
img_origin = cv2.imread('1.ImageProcess.jpg')
img_height, img_width, img_channels = img_origin.shape #获取图片尺寸高度、宽度、通道数
#cv2.imshow("windows_origin", img_origin) #窗口显示图片

#缩小图片尺寸，再次获取图片尺寸
img = cv2.resize(img_origin, (int(img_width/2),int(img_height/2)), interpolation=cv2.INTER_AREA)  
img_height, img_width, img_channels = img.shape 
cv2.imshow("windows", img) #显示图片缩小后的图片

mask = np.zeros((img_height, img_width, 1), dtype=np.uint8) + 1 #创建一张灰度图像
#cv2.calcHist([图片], [要统计直方图的通道], mask, [直方图横轴的坐标范围], [要统计的通道的取值范围])
#mask为掩膜，可以看作一张图片。效果为掩膜上灰度值为0的像素点的坐标为（x,y）,
#那么要统计直方图的图片对应坐标（x,y）上的像素点不加入直方图统计。None则统计图片全部像素点。
hist_B = cv2.calcHist([img], [0], mask, [100], [0,256])
hist_G = cv2.calcHist([img], [1], mask, [100], [0,256])
hist_R = cv2.calcHist([img], [2], mask, [100], [0,256])


###使用Pygal创建直方图
#使用Pygal创建直方图需要把数据先转换为整型
Hist_B_int=[]
Hist_G_int=[]
Hist_R_int=[]
for i in hist_B:
    Hist_B_int.append(int(i))
for i in hist_G:
    Hist_G_int.append(int(i))
for i in hist_R:
    Hist_R_int.append(int(i))

#使用Pygal创建蓝色直方图并保存为svg文件(使用浏览器打开)
hist_pygal_B=pygal.Bar()
hist_pygal_B.title="pygal_B"
hist_pygal_B.x_labels = range(0,100)
hist_pygal_B.add("Hist_B", Hist_B_int)
hist_pygal_B.render_to_file('pygal_B.svg')

#使用Pygal创建绿色直方图并保存为svg文件(使用浏览器打开)
hist_pygal_G=pygal.Bar()
hist_pygal_G.title="pygal_G"
hist_pygal_G.x_labels = range(0,100)
hist_pygal_G.add("Hist_G", Hist_G_int)
hist_pygal_G.render_to_file('pygal_G.svg')

#使用Pygal创建红色直方图并保存为svg文件(使用浏览器打开)
hist_pygal_R=pygal.Bar()
hist_pygal_R.title="pygal_R"
hist_pygal_R.x_labels = range(0,100)
hist_pygal_R.add("Hist_R", Hist_R_int)
hist_pygal_R.render_to_file('pygal_R.svg')
###使用Pygal创建直方图


###使用Plt创建直方图
#使用plt创建BGR彩色直方图
plt.figure("BGR_hist")
plt.title("Histogram of BGR")
plt.xlabel("Bins")
plt.ylabel("Numbers of Pixels")
plt.plot(hist_B,c='blue')
plt.plot(hist_G,c='green')
plt.plot(hist_R,c='red')
plt.xlim([0, 100])
plt.show()
###使用Plt创建直方图


