reader_infer.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. # coding: utf8
  2. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. import os.path as osp
  17. import numpy as np
  18. import math
  19. import cv2
  20. import argparse
  21. from paddlex import transforms as T
  22. import paddlex as pdx
  23. # 读数后处理中有把圆形表盘转成矩形的操作,矩形的宽即为圆形的外周长
  24. # 因此要求表盘图像大小为固定大小,这里设置为[512, 512]
  25. METER_SHAPE = [512, 512] # 高x宽
  26. # 圆形表盘的中心点
  27. CIRCLE_CENTER = [256, 256] # 高x宽
  28. # 圆形表盘的半径
  29. CIRCLE_RADIUS = 250
  30. # 圆周率
  31. PI = 3.1415926536
  32. # 在把圆形表盘转成矩形后矩形的高
  33. # 当前设置值约为半径的一半,原因是:圆形表盘的中心区域除了指针根部就是背景了
  34. # 我们只需要把外围的刻度、指针的尖部保存下来就可以定位出指针指向的刻度
  35. RECTANGLE_HEIGHT = 120
  36. # 矩形表盘的宽,即圆形表盘的外周长
  37. RECTANGLE_WIDTH = 1570
  38. # 当前案例中只使用了两种类型的表盘,第一种表盘的刻度根数为50
  39. # 第二种表盘的刻度根数为32。因此,我们通过预测的刻度根数来判断表盘类型
  40. # 刻度根数超过阈值的即为第一种,否则是第二种
  41. TYPE_THRESHOLD = 40
  42. # 两种表盘的配置信息,包含每根刻度的值,量程,单位
  43. METER_CONFIG = [{
  44. 'scale_interval_value': 25.0 / 50.0,
  45. 'range': 25.0,
  46. 'unit': "(MPa)"
  47. }, {
  48. 'scale_interval_value': 1.6 / 32.0,
  49. 'range': 1.6,
  50. 'unit': "(MPa)"
  51. }]
  52. # 分割模型预测类别id与类别名的对应关系
  53. SEG_CNAME2CLSID = {'background': 0, 'pointer': 1, 'scale': 2}
  54. def parse_args():
  55. parser = argparse.ArgumentParser(description='Meter Reader Infering')
  56. parser.add_argument(
  57. '--det_model_dir',
  58. dest='det_model_dir',
  59. help='The directory of the detection model',
  60. type=str)
  61. parser.add_argument(
  62. '--seg_model_dir',
  63. dest='seg_model_dir',
  64. help='The directory of the segmentation model',
  65. type=str)
  66. parser.add_argument(
  67. '--image_dir',
  68. dest='image_dir',
  69. help='The directory of images to be inferred',
  70. type=str,
  71. default=None)
  72. parser.add_argument(
  73. '--image',
  74. dest='image',
  75. help='The image to be inferred',
  76. type=str,
  77. default=None)
  78. parser.add_argument(
  79. '--use_erode',
  80. dest='use_erode',
  81. help='Whether erode the lable map predicted from a segmentation model',
  82. action='store_true')
  83. parser.add_argument(
  84. '--erode_kernel',
  85. dest='erode_kernel',
  86. help='Erode kernel size',
  87. type=int,
  88. default=4)
  89. parser.add_argument(
  90. '--save_dir',
  91. dest='save_dir',
  92. help='The directory for saving the predicted results',
  93. type=str,
  94. default='./output/result')
  95. parser.add_argument(
  96. '--score_threshold',
  97. dest='score_threshold',
  98. help="Predicted bounding boxes whose scores are lower than this threshlod are filtered",
  99. type=float,
  100. default=0.5)
  101. parser.add_argument(
  102. '--seg_batch_size',
  103. dest='seg_batch_size',
  104. help="The number of images fed into the segmentation model during one forward propagation",
  105. type=int,
  106. default=2)
  107. return parser.parse_args()
  108. def is_pic(img_name):
  109. """判断是否是图片
  110. 参数:
  111. img_name (str): 图片路径
  112. 返回:
  113. flag (bool): 判断值。
  114. """
  115. valid_suffix = ['JPEG', 'jpeg', 'JPG', 'jpg', 'BMP', 'bmp', 'PNG', 'png']
  116. suffix = img_name.split('.')[-1]
  117. flag = True
  118. if suffix not in valid_suffix:
  119. flag = False
  120. return flag
  121. class MeterReader:
  122. """检测表盘的位置,分割各表盘内刻度和指针的位置,并根据分割结果计算出各表盘的读数
  123. 参数:
  124. det_model_dir (str): 用于定位表盘的检测模型所在路径。
  125. seg_model_dir (str): 用于分割刻度和指针的分割模型所在路径。
  126. """
  127. def __init__(self, det_model_dir, seg_model_dir):
  128. if not osp.exists(det_model_dir):
  129. raise Exception("Model path {} does not exist".format(
  130. det_model_dir))
  131. if not osp.exists(seg_model_dir):
  132. raise Exception("Model path {} does not exist".format(
  133. seg_model_dir))
  134. self.detector = pdx.load_model(det_model_dir)
  135. self.segmenter = pdx.load_model(seg_model_dir)
  136. def decode(self, img_file):
  137. """图像解码
  138. 参数:
  139. img_file (str|np.array): 图像路径,或者是已解码的BGR图像数组。
  140. 返回:
  141. img (np.array): BGR图像数组。
  142. """
  143. if isinstance(img_file, str):
  144. img = cv2.imread(img_file).astype('float32')
  145. else:
  146. img = img_file.copy()
  147. return img
  148. def filter_bboxes(self, det_results, score_threshold):
  149. """过滤置信度低于阈值的检测框
  150. 参数:
  151. det_results (list[dict]): 检测模型预测接口的返回值。
  152. score_threshold (float):置信度阈值。
  153. 返回:
  154. filtered_results (list[dict]): 过滤后的检测狂。
  155. """
  156. filtered_results = list()
  157. for res in det_results:
  158. if res['score'] > score_threshold:
  159. filtered_results.append(res)
  160. return filtered_results
  161. def roi_crop(self, img, det_results):
  162. """抠取图像上各检测框的图像区域
  163. 参数:
  164. img (np.array):BRG图像数组。
  165. det_results (list[dict]): 检测模型预测接口的返回值。
  166. 返回:
  167. sub_imgs (list[np.array]): 各检测框的图像区域。
  168. """
  169. sub_imgs = []
  170. for res in det_results:
  171. # Crop the bbox area
  172. xmin, ymin, w, h = res['bbox']
  173. xmin = max(0, int(xmin))
  174. ymin = max(0, int(ymin))
  175. xmax = min(img.shape[1], int(xmin + w - 1))
  176. ymax = min(img.shape[0], int(ymin + h - 1))
  177. sub_img = img[ymin:(ymax + 1), xmin:(xmax + 1), :]
  178. sub_imgs.append(sub_img)
  179. return sub_imgs
  180. def resize(self, imgs, target_size, interp=cv2.INTER_LINEAR):
  181. """图像缩放至固定大小
  182. 参数:
  183. imgs (list[np.array]):批量BGR图像数组。
  184. target_size (list|tuple):缩放后的图像大小,格式为[高, 宽]。
  185. interp (int):图像差值方法。默认值为cv2.INTER_LINEAR。
  186. 返回:
  187. resized_imgs (list[np.array]):缩放后的批量BGR图像数组。
  188. """
  189. resized_imgs = list()
  190. for img in imgs:
  191. img_shape = img.shape
  192. scale_x = float(target_size[1]) / float(img_shape[1])
  193. scale_y = float(target_size[0]) / float(img_shape[0])
  194. resize_img = cv2.resize(
  195. img, None, None, fx=scale_x, fy=scale_y, interpolation=interp)
  196. resized_imgs.append(resize_img)
  197. return resized_imgs
  198. def seg_predict(self, segmenter, imgs, batch_size):
  199. """分割模型完成预测
  200. 参数:
  201. segmenter (pdx.seg.model):加载后的分割模型。
  202. imgs (list[np.array]):待预测的输入BGR图像数组。
  203. batch_size (int): 分割模型前向预测一次时输入图像的批量大小。
  204. 返回:
  205. seg_results (list[dict]): 输入图像的预测结果。
  206. """
  207. seg_results = list()
  208. num_imgs = len(imgs)
  209. for i in range(0, num_imgs, batch_size):
  210. batch = imgs[i:min(num_imgs, i + batch_size)]
  211. result = segmenter.predict(batch)
  212. seg_results.extend(result)
  213. return seg_results
  214. def erode(self, seg_results, erode_kernel):
  215. """对分割模型预测结果中label_map做图像腐蚀操作
  216. 参数:
  217. seg_results (list[dict]):分割模型的预测结果。
  218. erode_kernel (int): 图像腐蚀的卷积核的大小。
  219. 返回:
  220. eroded_results (list[dict]):对label_map进行腐蚀后的分割模型预测结果。
  221. """
  222. kernel = np.ones((erode_kernel, erode_kernel), np.uint8)
  223. eroded_results = seg_results
  224. for i in range(len(seg_results)):
  225. eroded_results[i]['label_map'] = cv2.erode(
  226. seg_results[i]['label_map'], kernel)
  227. return eroded_results
  228. def circle_to_rectangle(self, seg_results):
  229. """将圆形表盘的预测结果label_map转换成矩形
  230. 圆形到矩形的计算方法:
  231. 因本案例中两种表盘的刻度起始值都在左下方,故以圆形的中心点为坐标原点,
  232. 从-y轴开始逆时针计算极坐标到x-y坐标的对应关系:
  233. x = r + r * cos(theta)
  234. y = r - r * sin(theta)
  235. 注意:
  236. 1. 因为是从-y轴开始逆时针计算,所以r * sin(theta)前有负号。
  237. 2. 还是因为从-y轴开始逆时针计算,所以矩形从上往下对应圆形从外到内,
  238. 可以想象把圆形从-y轴切开再往左右拉平时,圆形的外围是上面,內围在下面。
  239. 参数:
  240. seg_results (list[dict]):分割模型的预测结果。
  241. 返回值:
  242. rectangle_meters (list[np.array]):矩形表盘的预测结果label_map。
  243. """
  244. rectangle_meters = list()
  245. for i, seg_result in enumerate(seg_results):
  246. label_map = seg_result['label_map']
  247. # rectangle_meter的大小已经由预先设置的全局变量RECTANGLE_HEIGHT, RECTANGLE_WIDTH决定
  248. rectangle_meter = np.zeros(
  249. (RECTANGLE_HEIGHT, RECTANGLE_WIDTH), dtype=np.uint8)
  250. for row in range(RECTANGLE_HEIGHT):
  251. for col in range(RECTANGLE_WIDTH):
  252. theta = PI * 2 * (col + 1) / RECTANGLE_WIDTH
  253. # 矩形从上往下对应圆形从外到内
  254. rho = CIRCLE_RADIUS - row - 1
  255. y = int(CIRCLE_CENTER[0] + rho * math.cos(theta) + 0.5)
  256. x = int(CIRCLE_CENTER[1] - rho * math.sin(theta) + 0.5)
  257. rectangle_meter[row, col] = label_map[y, x]
  258. rectangle_meters.append(rectangle_meter)
  259. return rectangle_meters
  260. def rectangle_to_line(self, rectangle_meters):
  261. """从矩形表盘的预测结果中提取指针和刻度预测结果并沿高度方向压缩成线状格式。
  262. 参数:
  263. rectangle_meters (list[np.array]):矩形表盘的预测结果label_map。
  264. 返回:
  265. line_scales (list[np.array]):刻度的线状预测结果。
  266. line_pointers (list[np.array]):指针的线状预测结果。
  267. """
  268. line_scales = list()
  269. line_pointers = list()
  270. for rectangle_meter in rectangle_meters:
  271. height, width = rectangle_meter.shape[0:2]
  272. line_scale = np.zeros((width), dtype=np.uint8)
  273. line_pointer = np.zeros((width), dtype=np.uint8)
  274. for col in range(width):
  275. for row in range(height):
  276. if rectangle_meter[row, col] == SEG_CNAME2CLSID['pointer']:
  277. line_pointer[col] += 1
  278. elif rectangle_meter[row, col] == SEG_CNAME2CLSID['scale']:
  279. line_scale[col] += 1
  280. line_scales.append(line_scale)
  281. line_pointers.append(line_pointer)
  282. return line_scales, line_pointers
  283. def mean_binarization(self, data_list):
  284. """对图像进行均值二值化操作
  285. 参数:
  286. data_list (list[np.array]):待二值化的批量数组。
  287. 返回:
  288. binaried_data_list (list[np.array]):二值化后的批量数组。
  289. """
  290. batch_size = len(data_list)
  291. binaried_data_list = data_list
  292. for i in range(batch_size):
  293. mean_data = np.mean(data_list[i])
  294. width = data_list[i].shape[0]
  295. for col in range(width):
  296. if data_list[i][col] < mean_data:
  297. binaried_data_list[i][col] = 0
  298. else:
  299. binaried_data_list[i][col] = 1
  300. return binaried_data_list
  301. def locate_scale(self, line_scales):
  302. """在线状预测结果中找到每根刻度的中心位置
  303. 参数:
  304. line_scales (list[np.array]):批量的二值化后的刻度线状预测结果。
  305. 返回:
  306. scale_locations (list[list]):各图像中每根刻度的中心位置。
  307. """
  308. batch_size = len(line_scales)
  309. scale_locations = list()
  310. for i in range(batch_size):
  311. line_scale = line_scales[i]
  312. width = line_scale.shape[0]
  313. find_start = False
  314. one_scale_start = 0
  315. one_scale_end = 0
  316. locations = list()
  317. for j in range(width - 1):
  318. if line_scale[j] > 0 and line_scale[j + 1] > 0:
  319. if find_start == False:
  320. one_scale_start = j
  321. find_start = True
  322. if find_start:
  323. if line_scale[j] == 0 and line_scale[j + 1] == 0:
  324. one_scale_end = j - 1
  325. one_scale_location = (
  326. one_scale_start + one_scale_end) / 2
  327. locations.append(one_scale_location)
  328. one_scale_start = 0
  329. one_scale_end = 0
  330. find_start = False
  331. scale_locations.append(locations)
  332. return scale_locations
  333. def locate_pointer(self, line_pointers):
  334. """在线状预测结果中找到指针的中心位置
  335. 参数:
  336. line_scales (list[np.array]):批量的指针线状预测结果。
  337. 返回:
  338. scale_locations (list[list]):各图像中指针的中心位置。
  339. """
  340. batch_size = len(line_pointers)
  341. pointer_locations = list()
  342. for i in range(batch_size):
  343. line_pointer = line_pointers[i]
  344. find_start = False
  345. pointer_start = 0
  346. pointer_end = 0
  347. location = 0
  348. width = line_pointer.shape[0]
  349. for j in range(width - 1):
  350. if line_pointer[j] > 0 and line_pointer[j + 1] > 0:
  351. if find_start == False:
  352. pointer_start = j
  353. find_start = True
  354. if find_start:
  355. if line_pointer[j] == 0 and line_pointer[j + 1] == 0:
  356. pointer_end = j - 1
  357. location = (pointer_start + pointer_end) / 2
  358. find_start = False
  359. break
  360. pointer_locations.append(location)
  361. return pointer_locations
  362. def get_relative_location(self, scale_locations, pointer_locations):
  363. """找到指针指向了第几根刻度
  364. 参数:
  365. scale_locations (list[list]):批量的每根刻度的中心点位置。
  366. pointer_locations (list[list]):批量的指针的中心点位置。
  367. 返回:
  368. pointed_scales (list[dict]):每个表的结果组成的list。每个表的结果由字典表示,
  369. 字典有两个关键词:'num_scales'、'pointed_scale',分别表示预测的刻度根数、
  370. 预测的指针指向了第几根刻度。
  371. """
  372. pointed_scales = list()
  373. for scale_location, pointer_location in zip(scale_locations,
  374. pointer_locations):
  375. num_scales = len(scale_location)
  376. pointed_scale = -1
  377. if num_scales > 0:
  378. for i in range(num_scales - 1):
  379. if scale_location[
  380. i] <= pointer_location and pointer_location < scale_location[
  381. i + 1]:
  382. pointed_scale = i + (
  383. pointer_location - scale_location[i]
  384. ) / (scale_location[i + 1] - scale_location[i] + 1e-05
  385. ) + 1
  386. result = {'num_scales': num_scales, 'pointed_scale': pointed_scale}
  387. pointed_scales.append(result)
  388. return pointed_scales
  389. def calculate_reading(self, pointed_scales):
  390. """根据刻度的间隔值和指针指向的刻度根数计算表盘的读数
  391. """
  392. readings = list()
  393. batch_size = len(pointed_scales)
  394. for i in range(batch_size):
  395. pointed_scale = pointed_scales[i]
  396. # 刻度根数大于阈值的为第一种表盘
  397. if pointed_scale['num_scales'] > TYPE_THRESHOLD:
  398. reading = pointed_scale['pointed_scale'] * METER_CONFIG[0][
  399. 'scale_interval_value']
  400. else:
  401. reading = pointed_scale['pointed_scale'] * METER_CONFIG[1][
  402. 'scale_interval_value']
  403. readings.append(reading)
  404. return readings
  405. def get_meter_reading(self, seg_results):
  406. """对分割结果进行读数后处理得到各表盘的读数
  407. 参数:
  408. seg_results (list[dict]): 分割模型的预测结果。
  409. 返回:
  410. meter_readings (list[dcit]): 各表盘的读数。
  411. """
  412. rectangle_meters = self.circle_to_rectangle(seg_results)
  413. line_scales, line_pointers = self.rectangle_to_line(rectangle_meters)
  414. binaried_scales = self.mean_binarization(line_scales)
  415. binaried_pointers = self.mean_binarization(line_pointers)
  416. scale_locations = self.locate_scale(binaried_scales)
  417. pointer_locations = self.locate_pointer(binaried_pointers)
  418. pointed_scales = self.get_relative_location(scale_locations,
  419. pointer_locations)
  420. meter_readings = self.calculate_reading(pointed_scales)
  421. return meter_readings
  422. def print_meter_readings(self, meter_readings):
  423. """打印各表盘的读数
  424. 参数:
  425. meter_readings (list[dict]):各表盘的读数
  426. """
  427. for i in range(len(meter_readings)):
  428. print("Meter {}: {}".format(i + 1, meter_readings[i]))
  429. def visualize(self, img, det_results, meter_readings, save_dir="./"):
  430. """可视化图像中各表盘的位置和读数
  431. 参数:
  432. img (str|np.array): 图像路径,或者是已解码的BGR图像数组。
  433. det_results (dict): 检测模型的预测结果。
  434. meter_readings (list): 各表盘的读数。
  435. save_dir (str):可视化后的图片保存路径。
  436. """
  437. vis_results = list()
  438. for i, res in enumerate(det_results):
  439. # 将检测结果中的关键词`score`替换成读数,就可以调用pdx.det.visualize画图了
  440. res['score'] = meter_readings[i]
  441. vis_results.append(res)
  442. # 检测结果可视化时会滤除score低于threshold的框,这里读数都是>=-1的,所以设置thresh=-1
  443. pdx.det.visualize(img, vis_results, threshold=-1, save_dir=save_dir)
  444. def predict(self,
  445. img_file,
  446. save_dir='./',
  447. use_erode=True,
  448. erode_kernel=4,
  449. score_threshold=0.5,
  450. seg_batch_size=2):
  451. """检测图像中的表盘,而后分割出各表盘中的指针和刻度,对分割结果进行读数后处理后得到各表盘的读数。
  452. 参数:
  453. img_file (str):待预测的图片路径。
  454. save_dir (str): 可视化结果的保存路径。
  455. use_erode (bool, optional): 是否对分割预测结果做图像腐蚀。默认值:True。
  456. erode_kernel (int, optional): 图像腐蚀的卷积核大小。默认值: 4。
  457. score_threshold (float, optional): 用于滤除检测框的置信度阈值。默认值:0.5。
  458. seg_batch_size (int, optional):分割模型前向推理一次时输入表盘图像的批量大小。默认值为:2。
  459. """
  460. img = self.decode(img_file)
  461. det_results = self.detector.predict(img)
  462. filtered_results = self.filter_bboxes(det_results, score_threshold)
  463. sub_imgs = self.roi_crop(img, filtered_results)
  464. sub_imgs = self.resize(sub_imgs, METER_SHAPE)
  465. seg_results = self.seg_predict(self.segmenter, sub_imgs,
  466. seg_batch_size)
  467. seg_results = self.erode(seg_results, erode_kernel)
  468. meter_readings = self.get_meter_reading(seg_results)
  469. self.print_meter_readings(meter_readings)
  470. self.visualize(img, filtered_results, meter_readings, save_dir)
  471. def infer(args):
  472. image_lists = list()
  473. if args.image is not None:
  474. if not osp.exists(args.image):
  475. raise Exception("Image {} does not exist.".format(args.image))
  476. if not is_pic(args.image):
  477. raise Exception("{} is not a picture.".format(args.image))
  478. image_lists.append(args.image)
  479. elif args.image_dir is not None:
  480. if not osp.exists(args.image_dir):
  481. raise Exception("Directory {} does not exist.".format(
  482. args.image_dir))
  483. for im_file in os.listdir(args.image_dir):
  484. if not is_pic(im_file):
  485. continue
  486. im_file = osp.join(args.image_dir, im_file)
  487. image_lists.append(im_file)
  488. meter_reader = MeterReader(args.det_model_dir, args.seg_model_dir)
  489. if len(image_lists) > 0:
  490. for image in image_lists:
  491. meter_reader.predict(image, args.save_dir, args.use_erode,
  492. args.erode_kernel, args.score_threshold,
  493. args.seg_batch_size)
  494. if __name__ == '__main__':
  495. args = parse_args()
  496. infer(args)