# 将调整后的数据转换为NumPy数组并进行预测 resized_test_data = np.array(resized_test_data) predictions = model.predict(resized_test_data) for i, pred in enumerate(predictions): filename = os.listdir(test_images)[i] new_filename = os.path.splitext(filename)[0] + '_prediction.png' # 构造新文件名 imageio.imwrite(new_filename, pred)怎么改
时间: 2024-02-11 13:10:06 浏览: 125
你可以使用OpenCV库来写入图像文件,可以将代码改为以下形式:
```python
import cv2
# 将调整后的数据转换为NumPy数组并进行预测
resized_test_data = np.array(resized_test_data)
predictions = model.predict(resized_test_data)
for i, pred in enumerate(predictions):
filename = os.listdir(test_images)[i]
new_filename = os.path.splitext(filename)[0] + '_prediction.png' # 构造新文件名
# 将预测结果转换为图像
pred = np.uint8(pred * 255) # 将像素值转换为0-255范围内的整数
pred = np.squeeze(pred) # 去除通道维度
pred = cv2.cvtColor(pred, cv2.COLOR_GRAY2BGR) # 将灰度图像转换为RGB图像
# 写入图像文件
cv2.imwrite(new_filename, pred)
```
这样可以将预测结果转换为RGB图像并使用OpenCV库写入图像文件。
相关问题
import os from time import time import numpy as np import matplotlib.pyplot as plt from PIL import Image from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.decomposition import PCA from sklearn.svm import SVC def load_data(path, image_size=(112, 92)): “”" 手动加载 ORL 数据集中的人脸图像。 返回 X 和 y 的数组形式。 “”" images = [] labels = [] for person_dir in sorted(os.listdir(path)): # 遍历每个人员目录 if not os.path.isdir(os.path.join(path, person_dir)): continue label = int(person_dir.split('_')[0]) - 1 # 假设目录名是以数字开头 for img_file in os.listdir(os.path.join(path, person_dir)): if img_file.endswith('.pgm'): img_path = os.path.join(path, person_dir, img_file) img = Image.open(img_path).convert('L') # 灰度化 img_resized = img.resize(image_size) # 转换到统一大小 img_array = np.array(img_resized, dtype=np.float64).flatten() / 255. images.append(img_array) labels.append(label) return np.array(images), np.array(labels) if name == ‘main’: data_path = r’D:\cxdownload\ORL人脸识别数据集’ print("Loading local face datasets...") t_start = time() X, Y = load_data(data_path) _, h, w = X.shape[0], 112, 92 target_names = [f"Person_{i}" for i in range(40)] n_classes = len(target_names) print(f"Total dataset size:") print(f"n_samples: {X.shape[0]}") print(f"n_features: {X.shape[1]}") print(f"n_classes: {n_classes}") print(f'done in {(time() - t_start):.3f}s') # 划分训练集与测试集 X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size=0.25, random_state=42) # 进行PCA降维 n_components = 150 print("Extracting the top {} eigenfaces from {} faces...".format( n_components, X_train.shape[0])) t0 = time() pca = PCA(n_components=n_components, svd_solver='randomized', whiten=True).fit(X_train) print("done in {:.3f}s".f
### 使用PCA进行人脸特征提取并用SVC完成分类
#### 数据预处理
在人脸识别任务中,通常会将每张人脸图像视为一个高维向量。为了减少计算复杂度和提高模型性能,可以通过主成分分析(Principal Component Analysis, PCA)降低数据维度[^3]。
```python
from sklearn.decomposition import PCA
import numpy as np
def preprocess_data(data, n_components=0.95):
"""
对输入的数据应用PCA降维。
参数:
data (numpy.ndarray): 输入的人脸图像矩阵,形状为(n_samples, n_features)。
n_components (float or int): 要保留的主成分数目或方差比例。
返回:
pca_result (numpy.ndarray): 经过PCA降维后的数据。
"""
pca = PCA(n_components=n_components, svd_solver='full')
pca_result = pca.fit_transform(data)
return pca_result
```
通过上述函数 `preprocess_data` 可以对原始数据集执行PCA操作,其中参数 `n_components` 表示要保留的主要成分数量或者希望保持的总方差百分比[^4]。
#### 构建支持向量机分类器
对于经过PCA降维后得到的新特征空间中的样本点,可以训练一个线性或非线性的支持向量机来区分不同的类别标签[^1]。
```python
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
def build_svm_classifier(features, labels):
"""
建立并评估基于SVM的支持向量机分类器。
参数:
features (numpy.ndarray): 特征矩阵,形状为(n_samples, n_reduced_dimensions)。
labels (list or array-like): 类别标签列表。
返回:
clf (sklearn.SVC): 训练好的SVM分类器实例。
test_accuracy (float): 测试集上的准确率得分。
"""
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
clf = SVC(kernel="linear", C=1.0, gamma="scale") # 初始化线性核SVM
clf.fit(X_train, y_train)
predictions = clf.predict(X_test)
test_accuracy = accuracy_score(y_test, predictions)
return clf, test_accuracy
```
这段代码定义了一个名为 `build_svm_classifier` 的方法用于创建SVM分类器,并返回该分类器及其测试精度值。
#### 完整流程演示
以下是结合以上两部分功能的一个简单例子:
```python
if __name__ == "__main__":
from sklearn.datasets import fetch_lfw_people
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
images = lfw_people.images.reshape((lfw_people.target.shape[0], -1))
targets = lfw_people.target
reduced_images = preprocess_data(images, n_components=0.85)
classifier, accuarcy = build_svm_classifier(reduced_images, targets)
print(f"SVM Classifier Accuracy on Test Set: {accuarcy:.2f}")
```
这里我们加载了LFW Faces数据集作为实验对象,调整其大小以便于快速运行程序;接着调用了前面编写的两个辅助函数完成了整个过程:先做PCA变换再送入到SVM里边去学习规律最后输出预测效果如何。
import cv2 import numpy as np import torch as torch from torchvision.models import densenet121 # Load the DenseNet model model = densenet121(pretrained=True) # Read the image image = cv2.imread('C:/Users/23594/Desktop/888.jpg') # Convert the image to grayscale grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Resize the image to the size of the model input resized_image = cv2.resize(grayscale_image, (224, 224)) # Normalize the image normalized_image = resized_image / 255.0 # Convert the image to a tensor image_tensor = torch.from_numpy(normalized_image).float() # Predict the key points of the person predictions = model(image_tensor) # Convert the predictions to a list of points points = [] for i in range(len(predictions[0])): points.append((predictions[0][i][0], predictions[0][i][1])) # Draw the key points on the image cv2.drawKeypoints(image, points, np.array([]), (0, 255, 0), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # Display the image cv2.imshow('Image', image) cv2.waitKey(0)import cv2 import numpy as np import torch as torch from torchvision.models import densenet121 # Load the DenseNet model model = densenet121(pretrained=True) # Read the image image = cv2.imread('C:/Users/23594/Desktop/888.jpg') # Convert the image to grayscale grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Resize the image to the size of the model input resized_image = cv2.resize(grayscale_image, (224, 224)) # Normalize the image normalized_image = resized_image / 255.0 # Convert the image to a tensor image_tensor = torch.from_numpy(normalized_image).float() # Predict the key points of the person predictions = model(image_tensor) # Convert the predictions to a list of points points = [] for i in range(len(predictions[0])): points.append((predictions[0][i][0], predictions[0][i][1])) # Draw the key points on the image cv2.drawKeypoints(image, points, np.array([]), (0, 255, 0), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # Display the image cv2.imshow('Image', image) cv2.waitKey(0)
这段代码是使用预训练的DenseNet模型对一张人物图片进行关键点检测,并在图片上标出关键点。它使用了OpenCV和PyTorch库。具体流程包括:
1. 导入必要的库,包括OpenCV、NumPy和PyTorch等。
2. 加载预训练的DenseNet模型。
3. 读取待检测的人物图片,并将其转为灰度图像。
4. 调整图片大小为与模型输入大小相同。
5. 将像素值归一化到0到1之间,并将其转为PyTorch的张量。
6. 对张量进行预测,得到关键点的坐标。
7. 将预测结果转为关键点的列表。
8. 在原始图片上标出关键点。
9. 显示标注后的图片。
需要注意的是,这段代码没有进行任何异常处理和参数调优,仅仅是演示了一个基本的关键点检测流程。
阅读全文
相关推荐

















