python图像识别代码
时间: 2024-06-22 16:03:41 浏览: 181
python 图片识别源码
5星 · 资源好评率100%
Python在图像识别领域非常流行,主要得益于其丰富的库和易用性。一种常见的图像识别方法是使用深度学习框架如TensorFlow或PyTorch,配合预训练模型如ResNet、VGG或Inception等。这里简单介绍一个基本流程:
1. 导入必要的库:
```python
import tensorflow as tf
from tensorflow.keras.applications import VGG16
from tensorflow.keras.preprocessing.image import img_to_array, load_img
```
2. 加载预训练模型(例如VGG16):
```python
model = VGG16(weights='imagenet', include_top=False)
```
3. 图像预处理:
```python
def preprocess_image(image_path):
img = load_img(image_path, target_size=(224, 224))
img_array = img_to_array(img) / 255.0
return np.expand_dims(img_array, axis=0)
```
4. 预测:
```python
image_path = 'path_to_your_image.jpg'
input_tensor = preprocess_image(image_path)
predictions = model.predict(input_tensor)
predicted_class = decode_predictions(predictions, top=1)
print(f"Predicted class: {predicted_class} ({predicted_class*100:.2f}% confidence)")
```
阅读全文