分别计算9、16、25等分图片总的HSI值的方差,并保存至Excel文件中 import cv2
import numpy as np
import os
from PIL import Image
import pandas as pd
import math
import openpyxl
from tqdm import tqdm
# 写封装函数,我给你一张图片,你返回一个结果
def get_image_paths(directory):
image_extensions = ['.jpg', '.png', '.bmp']
image_paths = []
file_name_list = []
for filename in os.listdir(directory):
if any(filename.endswith(ext) for ext in image_extensions):
image_paths.append(os.path.join(directory, filename))
file_name_list.append(filename)
return image_paths, file_name_list
def rgb_to_hsi(part_img):
# image = cv2.imread(img_path)
# image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 将BGR图像转换为RGB图像
height, width = part_img.shape[:2]
results = []
# 遍历图像的每个像素
for i in range(height):
for j in range(width):
# 获取像素(i, j)的RGB值
r, g, b = part_img[int(i), int(j)]
R = r / 255.0
G = g / 255.0
B = b / 255.0
def calc_h(r, g, b):
num = 0.5 * ((r - g) + (r - b))
den = np.sqrt((r - g) ** 2 + (r - b) * (g - b))
theta =math.acos(num / (den + 1e-10)) # 添加1e-10避免除零错误
if b <= g:
return theta
else:
return theta + 3.141592653589793
def calc_s(r, g, b):
min_val = min([r, g, b])
return 1 - 3.0 * min_val
def calc_i(r, g, b):
return (r + g + b) / 3.0
h = calc_h(R, G, B)
s = calc_s(R, G, B)
i = calc_i(R, G, B)
sum_hsi = h + s + i
results.append(sum_hsi)
all_sum = 0
for every_sum in results:
all_sum += every_sum
average = all_sum / len(results)
# return results
return average
def cutImage(hsi_Img, n):
read_img = cv2.imread(hsi_Img)
new_dimensions = (200, 200)
resized_image = cv2.resize(read_img, new_dimensions, interpolation=cv2.INTER_LINEAR)
height, width, channel = resized_image.shape
# Calculate the width and height of each part
part_width = width // n
part_height = height // n
parts = []
# Iterate over each part and crop it
for i in range(n):
for j in range(n):
# 计算每一个块的左上角坐标
left = i * part_width
top = j * part_height
# 计算每一块右下角的坐标
right = left + part_width
bottom = top + part_height
# Crop the image
cropped_img = read_img[top:bottom, left:right]
# Store the cropped part
parts.append(cropped_img)
return parts
def variance(input_every_average):
# 建立三个数组,用于保存所有的hsi值
n_variance = np.var(input_every_average)
return n_variance
def save2Excel(variance_list, save_path, column_name):
# 创建一个DataFrame对象
df = pd.DataFrame(variance_list, columns=column_name)
# 将DataFrame对象写入Excel文件
df.to_excel(save_path, index=False)
if __name__ == '__main__':
image_paths, file_name_list = get_image_paths('D:\\project\\dataset\\20230204172519')
average_arr = []
variance_list = []
for img_path in tqdm(image_paths):
parts = cutImage(img_path, 4)
for part in parts:
average = rgb_to_hsi(part)
average_arr.append(average)
# 求方差
n_variance = np.var(average_arr)
print(f"照片 {img_path} 的方差为 {n_variance}")
variance_list.append(n_variance)
newList_dict = {"fileName": file_name_list, "variance": variance_list}
xlsx = pd.DataFrame(newList_dict)
xlsx.to_excel("20230204172519_variance16.xlsx", index=False, engine='openpyxl') # 保存至相应的excel文件