class_labels = { 0: r'I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\result6\slic_pellucid\non-broken roofing', 1: r'I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\result6\slic_pellucid\broken roofing', 2: r'I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\result6\slic_pellucid\courtyard' }计算类被为1的像素点/(类别为+类别为的像素点)
时间: 2023-07-08 15:56:04 浏览: 79
根据您提供的代码,我可以看出这是一个Python字典类别标签和它们对应的路径。要计算类别为1的像素点占总像素点的比例,需要知道类别为1的像素点数和所有类别为1或类别为2的像素点数。代码如下:
```
import cv2
import numpy as np
# 读取图像
img = cv2.imread('your_image_path', cv2.IMREAD_GRAYSCALE)
# 类别为1的像素点数
class_1_pixels = np.sum(img == 1)
# 类别为1或类别为2的像素点数
total_pixels = np.sum(np.isin(img, [1, 2]))
# 计算比例
ratio = class_1_pixels / total_pixels
print('类别1像素点占比:', ratio)
```
请将 `your_image_path` 替换为您的图像路径。
相关问题
import cv2 import numpy as np import os # 提取图像的HOG特征 def get_hog_features(image): hog = cv2.HOGDescriptor() hog_features = hog.compute(image) return hog_features # 加载训练数据集 train_data = [r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128"] train_labels = [r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128\labels.txt"] num_samples = 681 for i in range(num_samples): img = cv2.imread(str(i).zfill(3)+'.jpg') hog_features = get_hog_features(image) hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) color_hist = cv2.calcHist([hsv_image], [0, 1], None, [180, 256], [0, 180, 0, 256]) color_features = cv2.normalize(color_hist, color_hist).flatten() train_data.append(hog_features) train_labels.append(labels[i]) # 训练SVM模型 svm = cv2.ml.SVM_create() svm.setType(cv2.ml.SVM_C_SVC) svm.setKernel(cv2.ml.SVM_LINEAR) svm.train(np.array(train_data), cv2.ml.ROW_SAMPLE, np.array(train_labels)) # 对测试图像进行分类 test_image = cv2.imread('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\maskslic2_roi.png', 0) test_features = get_hog_features(test_image) result = svm.predict(test_features.reshape(1,-1)) # 显示分割结果 result_image = np.zeros(test_image.shape, np.uint8) for i in range(test_image.shape[0]): for j in range(test_image.shape[1]): if result[i,j] == 1: result_image[i,j] = 255 cv2.imshow('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\Result.png', result_image) cv2.waitKey(0) cv2.destroyAllWindows()
这段代码似乎存在一些问题。以下是一些可能需要修改的地方:
1. 在加载训练数据时,`train_data`和`train_labels`应该是列表类型,而不是字符串类型。您可以使用`os.listdir()`函数来获取文件夹中的所有图像文件名,并使用`cv2.imread()`函数读取图像文件。
2. 在获取HOG特征时,您应该使用`img`而不是`image`变量。
3. 在提取颜色直方图特征时,您应该使用`test_image`而不是`image`变量。
4. 在将特征添加到`train_data`列表中时,您应该将`hog_features`和`color_features`链接在一起。
5. 在使用`svm.predict()`函数对测试图像进行分类时,您应该使用`svm.predict(test_features)`而不是`svm.predict(test_features.reshape(1,-1))`。
6. 在显示分割结果时,您应该使用`cv2.imshow()`函数的第一个参数是窗口的名称,而不是图像文件的路径。
以下是修改后的示例代码:
```python
import cv2
import numpy as np
import os
# 提取图像的HOG特征
def get_hog_features(img):
hog = cv2.HOGDescriptor()
hog_features = hog.compute(img)
return hog_features.flatten()
# 加载训练数据集
train_folder = r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128"
train_data = []
train_labels = []
for filename in os.listdir(train_folder):
if filename.endswith('.jpg'):
img = cv2.imread(os.path.join(train_folder, filename), 0)
hog_features = get_hog_features(img)
hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
color_hist = cv2.calcHist([hsv_image], [0, 1], None, [180, 256], [0, 180, 0, 256])
color_features = cv2.normalize(color_hist, color_hist).flatten()
features = np.concatenate((hog_features, color_features))
train_data.append(features)
with open(os.path.join(train_folder, 'labels.txt'), 'r') as f:
label = int(f.readline().strip())
train_labels.append(label)
# 训练SVM模型
svm = cv2.ml.SVM_create()
svm.setType(cv2.ml.SVM_C_SVC)
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.train(np.array(train_data), cv2.ml.ROW_SAMPLE, np.array(train_labels))
# 对测试图像进行分类
test_image = cv2.imread('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\maskslic2_roi.png', 0)
test_features = get_hog_features(test_image)
hsv_test_image = cv2.cvtColor(test_image, cv2.COLOR_BGR2HSV)
color_hist = cv2.calcHist([hsv_test_image], [0, 1], None, [180, 256], [0, 180, 0, 256])
color_features = cv2.normalize(color_hist, color_hist).flatten()
test_features = np.concatenate((test_features, color_features))
result = svm.predict(test_features)
# 显示分割结果
result_image = np.zeros(test_image.shape, np.uint8)
for i in range(test_image.shape[0]):
for j in range(test_image.shape[1]):
if result[i,j] == 1:
result_image[i,j] = 255
cv2.imshow('Result', result_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,以上代码仅作为参考。您可能需要根据自己的情况进行微调。
# 遍历每个类别 for class_label in class_labels: # 获取该类别对应的文件夹名称 folder_name = class_labels[class_label] folder_path = os.path.join(r'I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\result6\slic_pellucid', folder_name) # 初始化非透明像素点数量为 0 total_non_transparent_pixels = 0 # 遍历文件夹中的所有文件 for filename in os.listdir(folder_path): # 获取文件路径 filepath = os.path.join(folder_path, filename) # 判断是否为图像文件 if filepath.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')): # 计算非透明像素点数量 non_transparent_pixels = count_non_transparent_pixels(filepath) # 累加到总数中 total_non_transparent_pixels += non_transparent_pixels # 输出结果 print(f'类别 {class_label} 的非透明像素点总数:{total_non_transparent_pixels}')然后计算类别为1的像素点/(类别为1+类别为0的像素点)
可以在遍历完每个类别的非透明像素点数量后,将类别为1的非透明像素点数量和类别为0的非透明像素点数量相加,得到总的非透明像素点数量。然后就可以按照上面的方法计算类别为1的像素点占比了。
具体的实现代码如下:
```python
# 初始化类别为0和类别为1的非透明像素点总数为 0
total_non_transparent_pixels_0 = 0
total_non_transparent_pixels_1 = 0
# 遍历每个类别
for class_label in class_labels:
# 获取该类别对应的文件夹名称
folder_name = class_labels[class_label]
folder_path = os.path.join(r'I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\result6\slic_pellucid', folder_name)
# 初始化非透明像素点数量为 0
total_non_transparent_pixels = 0
# 遍历文件夹中的所有文件
for filename in os.listdir(folder_path):
# 获取文件路径
filepath = os.path.join(folder_path, filename)
# 判断是否为图像文件
if filepath.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
# 计算非透明像素点数量
non_transparent_pixels = count_non_transparent_pixels(filepath)
# 累加到总数中
total_non_transparent_pixels += non_transparent_pixels
# 输出结果
print(f'类别 {class_label} 的非透明像素点总数:{total_non_transparent_pixels}')
# 累加到类别为0或类别为1的非透明像素点总数中
if class_label == 0:
total_non_transparent_pixels_0 += total_non_transparent_pixels
elif class_label == 1:
total_non_transparent_pixels_1 += total_non_transparent_pixels
# 计算类别为1的像素点占比
total_non_transparent_pixels = total_non_transparent_pixels_0 + total_non_transparent_pixels_1
pixels_class_1 = total_non_transparent_pixels_1
if total_non_transparent_pixels > 0:
ratio_class_1 = pixels_class_1 / total_non_transparent_pixels
else:
ratio_class_1 = 0
print(f'类别为1的像素点占比:{ratio_class_1}')
```