import cv2
import matplotlib.pyplot as plt
# 读取彩色图像
image = cv2.imread('image.jpg')
# 将彩色图像转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 显示原图和灰度图像
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(gray_image, cmap='gray')
plt.title('Gray Image')
plt.axis('off')
plt.show()
# 查看灰度图像中背景和物体的灰度数据
background_threshold = 128 # 设定阈值,用于区分背景和物体
foreground_pixels = gray_image[gray_image < background_threshold] # 获取所有灰度值小于阈值的像素
background_pixels = gray_image[gray_image >= background_threshold] # 获取所有灰度值大于等于阈值的像素
print(f'Number of background pixels: {len(background_pixels)}')
print(f'Average background pixel value: {np.mean(background_pixels)}')
print(f'Standard deviation of background pixel values: {np.std(background_pixels)}')
print(f'Minimum background pixel value: {np.min(background_pixels)}')
print(f'Maximum background pixel value: {np.max(background_pixels)}')
print(f'Number of foreground pixels: {len(foreground_pixels)}')
print(f'Average foreground pixel value: {np.mean(foreground_pixels)}')
print(f'Standard deviation of foreground pixel values: {np.std(foreground_pixels)}')
print(f'Minimum foreground pixel value: {np.min(foreground_pixels)}')
print(f'Maximum foreground pixel value: {np.max(foreground_pixels)}')