代码如下:
import cv2
import numpy as np
from matplotlib import pyplot as plt
# 计算三波段协方差
'''
1.读取图像BGR三个波段的元素
2.分别计算三个波段元素平均值
3.计算cov协方差
4.得出协方差矩阵
'''
def Cov(image):
w = image.shape[0]
h = image.shape[1]
b = [0]*w*h
g = [0]*w*h
r = [0]*w*h
for i in range(w): # 获得BGR三个波段的像素值
for j in range(h):
for k in range(1):
B = image[i,j,k+0]
G = image[i,j,k+1]
R = image[i,j,k+2]
b[i*h+j] = B
g[i*h+j] = G
r[i*h+j] = R
# 计算平均值
all_b = 0 # 像素值总和
all_g = 0
all_r = 0
for i in range(w*h):
all_b += b[i]
all_g += g[i]
all_r += r[i]
mean_b = int(all_b/(w*h-1)) # 像素值平均值 取整
mean_g = int(all_g/(w*h-1))
mean_r = int(all_r/(w*h-1))
#计算协方差
cov_bb = 0
cov_bg = 0
cov_br = 0
cov_gb = 0
cov_gg = 0
cov_gr = 0
cov_rb = 0
cov_rg = 0
cov_rr = 0
for i in range(w*h):
cov_bb += (b[i]-mean_b)*(b[i]-mean_b)
cov_bg += (b[i]-mean_b)*(g[i]-mean_g)
cov_br += (b[i]-mean_b)*(r[i]-mean_r)
cov_gb += (g[i]-mean_g)*(b[i]-mean_b)
cov_gg += (g[i]-mean_g)*(g[i]-mean_g)
cov_gr += (g[i]-mean_g)*(r[i]-mean_r)
cov_rb += (r[i]-mean_r)*(b[i]-mean_b)
cov_rg += (r[i]-mean_r)*(g[i]-mean_g)
cov_rr += (r[i]-mean_r)*(r[i]-mean_r)
m = w*h-1
print('协方差矩阵:')
print(cov_bb/m,'\t',cov_bg/m,'\t',cov_br,'\n',cov_gb/m,'\t',cov_gg/m,'\t',cov_gr/m,'\n',cov_rb/m,'\t',cov_rg/m,'\t',cov_rr/m,'\n')
# 读入图像
image = cv2.imread('JuZi.jpg')
#cv2.imshow('Tu xiang',image)
Cov(image)
cv2.waitKey(0)
cv2.destroyAllWindows()