opencv-dnn

复制代码
# utils_words.txt  标签文件
import os


image_types = (".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff")


def list_images(basePath, contains=None):
    # return the set of files that are valid
    return list_files(basePath, validExts=image_types, contains=contains)


def list_files(basePath, validExts=None, contains=None):
    # loop over the directory structure
    for (rootDir, dirNames, filenames) in os.walk(basePath):
        # loop over the filenames in the current directory
        for filename in filenames:
            # if the contains string is not none and the filename does not contain
            # the supplied string, then ignore the file
            if contains is not None and filename.find(contains) == -1:
                continue

            # determine the file extension of the current file
            ext = filename[filename.rfind("."):].lower()

            # check to see if the file is an image and should be processed
            if validExts is None or ext.endswith(validExts):
                # construct the path to the image and yield it
                imagePath = os.path.join(rootDir, filename)
                yield imagePath

​
# 导入工具包
import utils_paths
import numpy as np
import cv2

# 标签文件处理
rows = open("synset_words.txt").read().strip().split("\n")
classes = [r[r.find(" ") + 1:].split(",")[0] for r in rows]

# Caffe所需配置文件
net = cv2.dnn.readNetFromCaffe("bvlc_googlenet.prototxt",
	"bvlc_googlenet.caffemodel")

# 图像路径
imagePaths = sorted(list(utils_paths.list_images("images/")))

# 图像数据预处理
image = cv2.imread(imagePaths[0])
resized = cv2.resize(image, (224, 224))
# image scalefactor size mean swapRB 
blob = cv2.dnn.blobFromImage(resized, 1, (224, 224), (104, 117, 123))
print("First Blob: {}".format(blob.shape))

# 得到预测结果
net.setInput(blob)
preds = net.forward()

# 排序,取分类可能性最大的
idx = np.argsort(preds[0])[::-1][0]
text = "Label: {}, {:.2f}%".format(classes[idx],
	preds[0][idx] * 100)
cv2.putText(image, text, (5, 25),  cv2.FONT_HERSHEY_SIMPLEX,
	0.7, (0, 0, 255), 2)

# 显示
cv2.imshow("Image", image)
cv2.waitKey(0)

# Batch数据制作
images = []

# 方法一样,数据是一个batch
for p in imagePaths[1:]:
	image = cv2.imread(p)
	image = cv2.resize(image, (224, 224))
	images.append(image)

# blobFromImages函数,注意有s
blob = cv2.dnn.blobFromImages(images, 1, (224, 224), (104, 117, 123))
print("Second Blob: {}".format(blob.shape))

# 获取预测结果
net.setInput(blob)
preds = net.forward()
for (i, p) in enumerate(imagePaths[1:]):
	image = cv2.imread(p)
	idx = np.argsort(preds[i])[::-1][0]
	text = "Label: {}, {:.2f}%".format(classes[idx],
		preds[i][idx] * 100)
	cv2.putText(image, text, (5, 25),  cv2.FONT_HERSHEY_SIMPLEX,
		0.7, (0, 0, 255), 2)
	cv2.imshow("Image", image)
	cv2.waitKey(0)

​
相关推荐
FITA阿泽要努力几秒前
/goal 命令:给 Agent 设定目标
服务器·人工智能·python·agent
志尊宝13 分钟前
AI原生前端开发(016):端侧AI与React 19结合实战
人工智能·react.js·ai-native
GPUStack13 分钟前
从 24 到 51 tok/s:用 GPUStack 调优 4 台 DGX Spark 上的 GLM 推理
人工智能·开源软件·gpustack·推理集群
leizhen1984080914 分钟前
操作系统正在被为智能体重做_上集(漫画)
人工智能·安全
BD_Marathon14 分钟前
【RAG开发】LangChain调用大语言模型
人工智能·语言模型·langchain
大鹏的NLP博客16 分钟前
工业视觉目标检测阈值选择与生产决策评估报告
人工智能·目标检测·图像检测
xiaoyunxuexibiji17 分钟前
供应商认证管理怎么做?从资质审核到现场认证、样品认证
运维·服务器·人工智能
嘉行文19 分钟前
传统机器学习与深度学习的特点与选择
人工智能·深度学习·机器学习
咕泡科技20 分钟前
深度学习碾压机器学习?经典机器学习是否真的无用了?从LLM底层逻辑到工业落地全景解析
人工智能·深度学习·机器学习·llm·nlp
腾讯云大数据29 分钟前
腾讯云AI Native数据平台功能发布合集【9月】
人工智能·腾讯云