当前位置:网站首页>Common function detect_ image/predict
Common function detect_ image/predict
2022-07-07 07:07:00 【Inverse summer 11111】
detect_image
#---------------------------------------------------#
# Test pictures
#---------------------------------------------------#
def detect_image(self, image):
start = timer()
image_shape = np.array(np.shape(image)[0:2])
crop_img, x_offset, y_offset = letterbox_image(image, (self.model_image_size[0], self.model_image_size[1]))
photo = np.array(crop_img, dtype=np.float64)
# Image preprocessing , normalization
photo = preprocess_input(np.reshape(photo, [1, self.model_image_size[0], self.model_image_size[1], 3]))
preds = self.ssd_model.predict(photo)
# Decode the prediction results
results = self.bbox_util.detection_out(preds, confidence_threshold=self.confidence)
# print(results)
if len(results[0]) <= 0:
return image, []
# Screen out those whose scores are higher than confidence Box of
det_label = results[0][:, 0]
det_conf = results[0][:, 1]
det_xmin, det_ymin, det_xmax, det_ymax = results[0][:, 2], results[0][:, 3], results[0][:, 4], results[0][:, 5]
top_indices = [i for i, conf in enumerate(det_conf) if conf >= self.confidence]
top_conf = det_conf[top_indices]
top_label_indices = det_label[top_indices].tolist()
top_xmin, top_ymin, top_xmax, top_ymax = np.expand_dims(det_xmin[top_indices], -1), np.expand_dims(
det_ymin[top_indices], -1), np.expand_dims(det_xmax[top_indices], -1), np.expand_dims(det_ymax[top_indices],
-1)
# Remove the gray strip
boxes = retinanet_correct_boxes(top_ymin, top_xmin, top_ymax, top_xmax,
np.array([self.model_image_size[0], self.model_image_size[1]]), image_shape)
font = ImageFont.truetype(font='model_data/simhei.ttf',
size=np.floor(3e-2 * np.shape(image)[1] + 0.5).astype('int32'))
thickness = (np.shape(image)[0] + np.shape(image)[1]) // self.model_image_size[0]
record_pred = []
for i, c in enumerate(top_label_indices):
predicted_class = self.class_names[int(c) - 1]
score = top_conf[i]
top, left, bottom, right = boxes[i]
top = top - 5
left = left - 5
bottom = bottom + 5
right = right + 5
top = max(0, np.floor(top + 0.5).astype('int32'))
left = max(0, np.floor(left + 0.5).astype('int32'))
bottom = min(np.shape(image)[0], np.floor(bottom + 0.5).astype('int32'))
right = min(np.shape(image)[1], np.floor(right + 0.5).astype('int32'))
print(top, left, bottom, right)
# Picture frame
label = '{} {:.2f}'.format(predicted_class, score)
draw = ImageDraw.Draw(image)
label_size = draw.textsize(label, font)
# label = label.encode('utf-8') # If this place is going to become utf8
print(label, (left, top), (right, bottom))
record_pred.append(label + " %s %s %s %s" % (left, top, right, bottom))
if top - label_size[1] >= 0:
text_origin = np.array([left, top - label_size[1]])
else:
text_origin = np.array([left, top + 1])
for i in range(thickness):
draw.rectangle(
[left + i, top + i, right - i, bottom - i],
outline=self.colors[int(c) - 1])
draw.rectangle(
[tuple(text_origin), tuple(text_origin + label_size)],
fill=self.colors[int(c) - 1])
draw.text(text_origin, label, fill=(0, 0, 0), font=font) # If the previous label Switch to utf-8 Here should be changed back :str(label,'UTF-8')
del draw
end = timer()
print("detect time:", end - start)
return image, record_pred
Different models need to be changed only : boxes = ssd_correct_boxes(top_ymin,top_xmin,top_ymax,top_xmax,np.array([self.model_image_size[0],self.model_image_size[1]]),image_shape)
Remove the part of the gray strip ,ssd The model is ssd_correct,retinanet The model is retinanet_correct... By analogy
predict
from keras.layers import Input
from retinanet import Retinanet
from PIL import Image
import os
retinanet = Retinanet()
img_path = "data/train1/domain1" # TODO: Enter the image folder to test
predict_path = "mAP/predict/"
filename_list = os.listdir(img_path)
for filename in filename_list:
print(filename)
img = input(filename)
try:
image = Image.open(img)
except:
print('Open Error! Try again!')
else:
r_image,record_pred = retinanet.detect_image(image)
with open(predict_path + filename.split(".")[0] + '.txt', "w") as f:
f.write("\n".join(record_pred))
# r_image.save("mAP/predict_images/"+filename)
retinanet.close_session()
边栏推荐
- 毕业设计游戏商城
- Answer to the first stage of the assignment of "information security management and evaluation" of the higher vocational group of the 2018 Jiangsu Vocational College skills competition
- linux系统rpm方式安装的mysql启动失败
- 企業如何進行數據治理?分享數據治理4個方面的經驗總結
- Stack and queue-p79-10 [2014 unified examination real question]
- 多学科融合
- MySQL binlog related commands
- 使用TCP/IP四层模型进行网络传输的基本流程
- 2018年江苏省职业院校技能大赛高职组“信息安全管理与评估”赛项任务书第一阶段答案
- 数据资产管理与数据安全国内外最新趋势
猜你喜欢
![[noi simulation] regional division (conclusion, structure)](/img/7d/4c66cd0a30e52ccd167b6138fcb4df.png)
[noi simulation] regional division (conclusion, structure)

LC 面试题 02.07. 链表相交 & LC142. 环形链表II

unity3d学习笔记

$parent(获取父组件) 和 $root(获取根组件)

企業如何進行數據治理?分享數據治理4個方面的經驗總結

从零到一,教你搭建「CLIP 以文搜图」搜索服务(二):5 分钟实现原型

What books can greatly improve programming ideas and abilities?

Redhat5 installing vmware tools under virtual machine

7天零基础能考证HCIA吗?华为认证系统学习路线分享

Answer to the second stage of the assignment of "information security management and evaluation" of the higher vocational group of the 2018 Jiangsu Vocational College skills competition
随机推荐
Matlab tips (29) polynomial fitting plotfit
Libcurl returns curlcode description
SVN version management in use replacement release and connection reset
Implementation of AVL tree
Exception of DB2 getting table information: caused by: com ibm. db2.jcc. am. SqlException: [jcc][t4][1065][12306][4.25.13]
[Luogu p1971] rabbit and egg game (bipartite game)
Network foundation - header, encapsulation and unpacking
jdbc数据库连接池使用问题
[GNN] graphic gnn:a gender Introduction (including video)
How can clothing stores make profits?
Matlab tips (30) nonlinear fitting lsqcurefit
分布式id解决方案
RuntimeError: CUDA error: CUBLAS_ STATUS_ ALLOC_ Failed when calling `cublascreate (handle) `problem solving
Stack and queue-p79-10 [2014 unified examination real question]
SolidWorks的GB库(钢型材库,包括铝型材、铝管等结构)安装及使用教程(生成铝型材为例)
Take you to brush (niuke.com) C language hundred questions (the first day)
unity3d学习笔记
Master-slave replication principle of MySQL
The latest trends of data asset management and data security at home and abroad
from .onnxruntime_pybind11_state import * # noqa ddddocr运行报错