在opencv使用Jupyter代码写一个图片识别程序
时间: 2024-05-08 16:15:19 浏览: 95
基于OpenCV实现的图片识别功能源码
3星 · 编辑精心推荐
以下是一个基础的图片识别程序,可以通过改变模型和图片来进行不同的识别任务。
首先,我们需要导入必要的库和模型:
```python
import cv2
import matplotlib.pyplot as plt
import numpy as np
# 导入模型
model = cv2.dnn.readNetFromCaffe('models/deploy.prototxt', 'models/res10_300x300_ssd_iter_140000_fp16.caffemodel')
```
然后,我们选择一张图片进行识别:
```python
image = cv2.imread('images/test.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
```
接下来,我们对图片进行预处理,并使用模型进行识别:
```python
# 预处理图片
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
# 使用模型进行识别
model.setInput(blob)
detections = model.forward()
```
最后,我们将识别结果绘制在图片上并展示:
```python
# 绘制识别结果
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.5:
box = detections[0, 0, i, 3:7] * np.array([image.shape[1], image.shape[0], image.shape[1], image.shape[0]])
(startX, startY, endX, endY) = box.astype("int")
label = '{:.2f}%'.format(confidence * 100)
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(image, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 展示结果
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
plt.imshow(image)
plt.show()
```
完整代码如下:
```python
import cv2
import matplotlib.pyplot as plt
import numpy as np
# 导入模型
model = cv2.dnn.readNetFromCaffe('models/deploy.prototxt', 'models/res10_300x300_ssd_iter_140000_fp16.caffemodel')
# 读取图片
image = cv2.imread('images/test.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
# 预处理图片
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
# 使用模型进行识别
model.setInput(blob)
detections = model.forward()
# 绘制识别结果
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.5:
box = detections[0, 0, i, 3:7] * np.array([image.shape[1], image.shape[0], image.shape[1], image.shape[0]])
(startX, startY, endX, endY) = box.astype("int")
label = '{:.2f}%'.format(confidence * 100)
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(image, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 展示结果
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
plt.imshow(image)
plt.show()
```
阅读全文