image_detect.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. #!/usr/bin/env python
  2. # -*- coding=utf-8 -*-
  3. import os
  4. import numpy as np
  5. import base64
  6. import cv2
  7. import json
  8. import logging
  9. import logging.config
  10. import importlib
  11. import time
  12. import sys
  13. import traceback
  14. from os import path
  15. import uuid
  16. reload(sys)
  17. sys.setdefaultencoding('utf8')
  18. cdir =os.path.dirname(__file__)
  19. # logging.basicConfig(filename=os.path.join(cdir, 'AIServer.log'),
  20. # filemode='a',format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
  21. # level=logging.DEBUG)
  22. if sys.platform.find('linux') >= 0:
  23. logging.basicConfig( format='%(asctime)s [%(levelname)s] - %(message)s', level=logging.INFO)
  24. else:
  25. with open(os.path.join(cdir, 'log.config'), 'rt') as f:
  26. lcnf = json.load(f)
  27. logging.config.dictConfig(lcnf)
  28. vi_lib_dir = os.getenv('VI_LIB')
  29. vi_opton_dir = os.getenv('VI_OPTON')
  30. opton_pred_dir = os.path.join(vi_opton_dir, 'opton_pred_v2')
  31. sys.path.append(vi_lib_dir)
  32. sys.path.append(vi_opton_dir)
  33. sys.path.append(opton_pred_dir)
  34. logging.debug('vi_lib_dir: ' + vi_lib_dir)
  35. logging.debug('vi_opton_dir: ' + vi_opton_dir)
  36. logging.debug('opton_pred_dir: ' + opton_pred_dir)
  37. logging.debug('sys.path: ' + str(sys.path))
  38. idir = os.path.join(cdir, 'web', 'images')
  39. if not os.path.exists(idir):
  40. os.makedirs(idir)
  41. hdir = 'http://127.0.0.1:7999/images/'
  42. from opton_core.const import *
  43. from opton_core.font_util import get_font_scale_and_thick
  44. from opton_core.read_image_scale import read_scale
  45. import opton_core.translate_zzsb as translate_zzsb
  46. import opton_core.translate_bzpj as translate_bzpj
  47. from opton_pred_v2.config import get_task_models
  48. from opton_pred_v2.pred import pred_zzsb_image
  49. from opton_pred_v2.pred import pred_bzpj_image
  50. class NumpyEncoder(json.JSONEncoder):
  51. """ Special json encoder for numpy types """
  52. def default(self, obj):
  53. if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
  54. np.int16, np.int32, np.int64, np.uint8,
  55. np.uint16, np.uint32, np.uint64)):
  56. return int(obj)
  57. elif isinstance(obj, (np.float_, np.float16, np.float32,
  58. np.float64)):
  59. return float(obj)
  60. elif isinstance(obj,(np.ndarray,)):
  61. return obj.tolist()
  62. return json.JSONEncoder.default(self, obj)
  63. def get_image_scale(img_base64):
  64. im_str = base64.b64decode(img_base64)
  65. im_inp = np.fromstring(im_str, dtype=np.uint8)
  66. im_inp = cv2.imdecode(im_inp, 1)
  67. zoom_key, um_per_pix, _ = read_scale(im_inp)
  68. try:
  69. return parseResult(True, {"zoom_key":zoom_key,"um_per_pix":round(um_per_pix,4)})
  70. except Exception as e:
  71. logging.error(traceback.format_exc())
  72. return parseResult(False, {"msg":"Failed to get the scale, please check the image"})
  73. def parseResult(success, raw_msg):
  74. smsg = ""
  75. try:
  76. json_msg = {"success":success, "content": raw_msg}
  77. logging.debug(json_msg)
  78. smsg = json.dumps(json_msg, ensure_ascii=False, cls=NumpyEncoder)
  79. except Exception as e:
  80. logging.error(e)
  81. json_msg = {"success":False, "content": "Invalid for the result."}
  82. smsg = json.dumps(json_msg, ensure_ascii=False)
  83. return smsg.decode("utf-8")
  84. def check_json_format(raw_msg):
  85. try:
  86. logging.debug(raw_msg.encode("utf-8"))
  87. json_msg = json.loads(raw_msg.encode("utf-8"))
  88. return True, json_msg
  89. except ValueError:
  90. try:
  91. json_msg = json.loads(raw_msg)
  92. return True, json_msg
  93. except ValueError:
  94. return False, {}
  95. class ImageDetect:
  96. def __init__(self):
  97. logging.debug('ImageDetect class is initialised.')
  98. self.sfunc = ''
  99. self.scatagory = -1
  100. self.sstatus = -1
  101. self.smaginifiation = -1
  102. self.sitems = -1
  103. self.task = None
  104. def init(self, args):
  105. logging.debug('init function is called:'+args)
  106. args_ok, jargs = check_json_format(args)
  107. if (args_ok == False):
  108. logging.error("Invalid input parameter:"+args)
  109. return parseResult(False, {"msg":"Invalid input parameter"})
  110. try:
  111. sfunc = jargs['func']
  112. self.sfunc = sfunc
  113. if sfunc == 'zzsb':
  114. scatagory = jargs['catagory']
  115. sstatus = jargs['status']
  116. smaginifiation = jargs['magnification']
  117. logging.debug('zzsb init: '+scatagory + ":" + sstatus + ":" + smaginifiation)
  118. self.scatagory = int(scatagory)
  119. self.sstatus = int(sstatus)
  120. self.smaginifiation = int(smaginifiation)
  121. elif sfunc == 'bzpj':
  122. scatagory = jargs['catagory']
  123. sitems = jargs['items']
  124. logging.debug('bzpj init: '+scatagory + ":" + sitems)
  125. self.scatagory = int(scatagory)
  126. self.sitems = int(sitems)
  127. jargs.pop('catagory')
  128. jargs.pop('items')
  129. jargs.pop('func')
  130. else :
  131. logging.error('unsupport function: '+sfunc)
  132. return parseResult(False, {"msg":"unsupport function"})
  133. except:
  134. logging.error(traceback.format_exc())
  135. return parseResult(False, {"msg":"Missing parameters"})
  136. self.times = 0
  137. return parseResult(True, {"msg":"Call init method success."})
  138. def get_vp(self, im_inp, args):
  139. h, w = im_inp.shape[:2]
  140. vp = {}
  141. vp['type'] = 'R'
  142. vp['x'] = 0
  143. vp['y'] = 0
  144. vp['w'] = w
  145. vp['h'] = h
  146. # vp params
  147. if args.has_key('viewport'):
  148. vp = args['viewport']
  149. return vp
  150. def overlay_im_out_on_im_inp(self, im_out, im_inp, args):
  151. if im_out is None:
  152. return
  153. h, w = im_inp.shape[:2]
  154. vp = self.get_vp(im_inp, args)
  155. x1 = vp['x']
  156. y1 = vp['y']
  157. x2 = vp['x'] + vp['w']
  158. y2 = vp['y'] + vp['h']
  159. color = (0,0,255)
  160. font = cv2.FONT_HERSHEY_SIMPLEX
  161. scale, thick = get_font_scale_and_thick(im_inp)
  162. # blur
  163. im_inp = cv2.blur(im_inp, (30,30))
  164. if vp['type'] == 'R':
  165. im_inp[y1:y2, x1:x2, :] = im_out
  166. # draw vp border
  167. # if vp['w'] < w or vp['h'] < h:
  168. # cv2.rectangle(im_inp[y1:y2, x1:x2, :], (x1,y1), (x2,y2), color, thick)
  169. else:
  170. im_out_fg_mask = np.zeros((vp['h'], vp['w']), np.uint8)
  171. cx = int(vp['w']/2)
  172. cy = int(vp['h']/2)
  173. r = int(min(vp['w'], vp['h']) / 2)
  174. cv2.circle(im_out_fg_mask, (cx,cy), r, (255,255,255), -1)
  175. im_out_fg = cv2.bitwise_and(im_out, im_out, mask=im_out_fg_mask)
  176. im_vp = im_inp[y1:y2, x1:x2, :]
  177. im_out_bg_mask = cv2.bitwise_not(im_out_fg_mask)
  178. im_out_bg = cv2.bitwise_and(im_vp, im_vp, mask=im_out_bg_mask)
  179. im_inp[y1:y2, x1:x2, :] = cv2.add(im_out_bg, im_out_fg)
  180. # draw vp border
  181. # cv2.circle(im_inp[y1:y2, x1:x2, :], (cx,cy), r, color, thick)
  182. return im_inp
  183. def draw_text(self, im_inp, text, x, y, color, shade=False):
  184. scale, thick = get_font_scale_and_thick(im_inp)
  185. # print("scale=",scale)
  186. # scale=2
  187. if scale>3 :
  188. scale=3
  189. font = cv2.FONT_HERSHEY_SIMPLEX
  190. offset = thick
  191. if shade:
  192. # cv2.putText(im_inp, text, (x+offset, y+offset), font, scale, (255,255,255), thick)
  193. cv2.putText(im_inp, text, (x, y), font, scale, (255,255,255), thick*4)
  194. cv2.putText(im_inp, text, (x, y), font, scale, color, thick)
  195. def draw_bbox(self, im_inp, bbox, color, shade=False):
  196. (x1,y1,x2,y2) = bbox
  197. scale, thick = get_font_scale_and_thick(im_inp)
  198. font = cv2.FONT_HERSHEY_SIMPLEX
  199. offset = thick
  200. if shade:
  201. # cv2.rectangle(im_inp, (x1+offset,y1x1+offset), (x2x1+offset,y2x1+offset), (255,255,255), thick)
  202. cv2.rectangle(im_inp, (x1,y1), (x2,y2), (255,255,255), thick*4)
  203. cv2.rectangle(im_inp, (x1,y1), (x2,y2), color, thick)
  204. def do_pred_by_data(self, img_base64, args={}):
  205. logging.debug("call start to do_pred_by_data---->")
  206. im_str = base64.b64decode(img_base64)
  207. im_inp = np.fromstring(im_str, dtype=np.uint8)
  208. im_inp = cv2.imdecode(im_inp, 1)
  209. h, w = im_inp.shape[:2]
  210. vp = self.get_vp(im_inp, args)
  211. title = ''
  212. details = {}
  213. im_out = None
  214. zoom_key = ''
  215. um_per_pix = -1
  216. image_http = ''
  217. image_path = ''
  218. task_name = None
  219. cls_name = None
  220. font = cv2.FONT_HERSHEY_SIMPLEX
  221. scale, thick = get_font_scale_and_thick(im_inp)
  222. is_success = True
  223. try:
  224. if self.sfunc == 'zzsb':
  225. logging.debug("pred_zzsb_image ---->")
  226. title, details, im_out, (self.task, task_name, cls_name, zoom_key, um_per_pix) = pred_zzsb_image(im_inp, args)
  227. # translate names
  228. title = translate_zzsb.translate_title(title)
  229. details = translate_zzsb.translate_details(details)
  230. logging.debug("pred_zzsb_image title: " + title)
  231. # overlay im_out on im_inp
  232. im_inp = self.overlay_im_out_on_im_inp(im_out, im_inp, args)
  233. if args.has_key('draw_color_zz') and len(args['draw_color_zz']) > 0:
  234. # draw percent text
  235. offset = scale * 40
  236. x = 20
  237. y = 20
  238. # details: {'class_name': (percent, sample_bbox, dets, color), ...}
  239. for k, v in details.items():
  240. color = v[3]
  241. if color is None:
  242. # indicate the class_name is not in draw_color_zz list
  243. continue
  244. y = y + offset
  245. if v[0] == 1.0:
  246. text = '{}: 100%'.format(k)
  247. else:
  248. text = '{}: {:.2%}'.format(k, v[0])
  249. self.draw_text(im_inp, text, x, y, color, True)
  250. else:
  251. # draw sample bboxes on im_inp
  252. color = (0,0,255)
  253. for key, value in details.items():
  254. # draw sample bbox
  255. (x1,y1,x2,y2) = value[1]
  256. bg=value[3]
  257. if bg ==None:
  258. margin = 20
  259. x1 = max(vp['x']+x1-margin, 0)
  260. y1 = max(vp['y']+y1-margin, 0)
  261. x2 = min(vp['x']+x2+margin, w)
  262. y2 = min(vp['y']+y2+margin, h)
  263. self.draw_bbox(im_inp, (x1,y1,x2,y2), color, True)
  264. # draw bbox text
  265. margin = 10
  266. x = x1
  267. y = y1 - margin
  268. if y < margin:
  269. y = y2 + margin*3
  270. self.draw_text(im_inp, key, x, y, color, True)
  271. else:
  272. self.draw_text(im_inp, key,vp['x']+30,vp['y']+100, color, True)
  273. elif self.sfunc == 'bzpj':
  274. logging.debug("pred_bzpj_image ---->")
  275. title, details, im_out, (self.task, task_name, cls_name, zoom_key, um_per_pix) = pred_bzpj_image(im_inp.copy(), self.scatagory, self.sitems, args)
  276. title = str(title)
  277. logging.debug("pred_bzpj_image title: " + title)
  278. # overlay im_out on im_inp
  279. im_inp = self.overlay_im_out_on_im_inp(im_out, im_inp, args)
  280. # details: {'results': [(text, color),], ...}
  281. if details is not None and details.has_key('results'):
  282. offset = scale * 40
  283. x = 20
  284. y = 40*scale
  285. for (text, color) in details['results']:
  286. size=cv2.getTextSize(text,cv2.FONT_HERSHEY_COMPLEX,3,2)
  287. print("size=",size)
  288. self.draw_text(im_inp, text, x, y, color, True)
  289. x +=size[0][0]+20
  290. title_base64 = base64.b64encode(title)
  291. image_name = str(time.strftime('%Y%m%d_%H%M%S_' , time.localtime())) + str(uuid.uuid1())[:8] + ".jpg"
  292. image_path = os.path.join(idir, image_name).decode("utf-8")
  293. cv2.imencode(image_path, im_inp)[1].tofile(image_path)
  294. image_http = (hdir+image_name).decode("utf-8")
  295. except:
  296. logging.error(traceback.format_exc())
  297. is_success = False
  298. detect = {
  299. "title": title,
  300. "details": details,
  301. "detect_type": self.sfunc,
  302. "viewport": vp,
  303. "additional": {
  304. "zoom_key":zoom_key,
  305. "um_per_pix":um_per_pix,
  306. "task_name":task_name,
  307. "cls_name":cls_name,
  308. "pred_image":image_http,
  309. "image_path":image_path
  310. }
  311. }
  312. jresult = parseResult(is_success, detect)
  313. logging.debug(jresult)
  314. logging.debug("call end of do_pred_by_data<----")
  315. return jresult
  316. '''
  317. NOT USED by now
  318. '''
  319. def do_pred_by_file(self, param):
  320. logging.debug("call start to do_pred_by_file---->")
  321. logging.debug(param.encode("utf-8"))
  322. im_inp = self.task.load_image_file(param.encode("utf-8"))
  323. title, details = self.task.pred_img_data(im_inp)
  324. zoom_key, um_per_pix = self.task.read_image_scale(im_inp)
  325. title = translate_zzsb.translate_title(title)
  326. details = translate_zzsb.translate_details(details)
  327. detect = {"title":title, "details":details, "additional":{"zoom_key":zoom_key, "um_per_pix":um_per_pix}}
  328. jresult = parseResult(True, detect)
  329. logging.debug(jresult)
  330. logging.debug("call end of do_pred_by_file<----")
  331. return jresult
  332. if __name__ == '__main__':
  333. jpg_name = sys.argv[1]
  334. cur_dir = os.getcwd()
  335. test_dir = os.path.join(cur_dir, 'test')
  336. jpg_file = os.path.join(test_dir, jpg_name + '.jpg')
  337. img = cv2.imread(jpg_file)
  338. x=0
  339. y=0
  340. h, w = img.shape[:2]
  341. r = 800
  342. cx = int(w/2) - r
  343. cy = int(h/2) - r
  344. cw = r * 2
  345. ch = r * 2
  346. img = cv2.imencode('.jpg', img)[1]
  347. img = base64.b64encode(img)
  348. ai = ImageDetect()
  349. params = {}
  350. # =================================================================
  351. # Used for demonstrating all supported custom parameters
  352. # =================================================================
  353. if jpg_name == 'z1_1':
  354. # ZZSB-a-alpha_f
  355. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  356. params = {
  357. # 'zoom_key': 500,
  358. # 'um_per_pix': 0.049,
  359. 'draw_color_zz':['alphaf'],
  360. # 'input': [
  361. # {'shape_type':'rect', 'shape_data':[(x1,y1),(x2,y2)], 'value':'alphaf', 'action':'add'},
  362. # {'shape_type':'rect', 'shape_data':[(x1,y1),(x2,y2)], 'value':'', 'action':'delete'}
  363. # ]
  364. }
  365. if jpg_name == 'z1_2':
  366. # ZZSB-a-alpha_f
  367. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  368. params = {
  369. # 'zoom_key': 500,
  370. # 'um_per_pix': 0.049,
  371. 'draw_color_zz':['alphaf'],
  372. # 'input': [
  373. # {'shape_type':'rect', 'shape_data':[(x1,y1),(x2,y2)], 'value':'alphaf', 'action':'add'},
  374. # {'shape_type':'rect', 'shape_data':[(x1,y1),(x2,y2)], 'value':'', 'action':'delete'}
  375. # ]
  376. }
  377. if jpg_name == 'z2':
  378. # ZZSB-a-f
  379. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  380. params = {'draw_color_zz':['a', 'f']}
  381. if jpg_name == 'z3':
  382. # ZZSB-b-p-f
  383. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  384. params = {'draw_color_zz':['f', 'p']}
  385. if jpg_name == 'z4':
  386. # ZZSB-f-p
  387. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  388. params = {'draw_color_zz':['p']}
  389. if jpg_name == 'z5':
  390. # ZZSB-g_p-ps_c
  391. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  392. params = {'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch}}
  393. if jpg_name == 'z6':
  394. # ZZSB-m-cem-retain_a
  395. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  396. if jpg_name == 'z7':
  397. # ZZSB-m
  398. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  399. if jpg_name == 'z8':
  400. # ZZSB-p-f
  401. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  402. params = {'draw_color_zz':['p']}
  403. if jpg_name == 'z9':
  404. # ZZSB-p
  405. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  406. params = {'draw_color_zz':['p']}
  407. if jpg_name == 'z10':
  408. # ZZSB-tempm-cem-retain_a
  409. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  410. if jpg_name == 'z11':
  411. # ZZSB-temps
  412. ai.init('{"func": "zzsb", "catagory": "-1", "status": "-1", "magnification": "-1"}')
  413. params = {'draw_color_zz':['deltaf']}
  414. # ------------------------------------------------------------------------------
  415. if jpg_name == '14_1':
  416. # ZT_H-G_XZ
  417. ai.init('{"func":"bzpj", "catagory":"14", "items":"1"}')
  418. params = {
  419. # 'input': [
  420. # {'shape_type':'rect', 'shape_data':[(x1,y1),(x2,y2)], 'value':'A', 'action':'add'}
  421. # ]
  422. }
  423. if jpg_name == '14_2':
  424. # ZT_H-G_CD
  425. ai.init('{"func":"bzpj", "catagory":"14", "items":"2"}')
  426. params = {
  427. 'zoom_key': 100,
  428. 'um_per_pix': 0.407,
  429. 'input': [
  430. {'shape_type': 'line', 'shape_data': [[50, 228], [478, 600]], 'action': 'add', 'value': ''},
  431. {'shape_type': 'line', 'shape_data': [(280, 1062), (746, 704)], 'action': 'add', 'value': ''},
  432. {'shape_type': 'line', 'shape_data': [(2144, 906), (1784, 1112)], 'action': 'add', 'value': ''}
  433. ]
  434. }
  435. if jpg_name == '14_3':
  436. # ZT_H-P_SL
  437. ai.init('{"func":"bzpj", "catagory":"14", "items":"3"}')
  438. params = {'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch}}
  439. if jpg_name == '14_5':
  440. # ZT_H-LGJ_SL
  441. ai.init('{"func":"bzpj", "catagory":"14", "items":"5"}')
  442. params = {'viewport': {'type':'C', 'x':496, 'y':224, 'w':1759, 'h':1759}}
  443. if jpg_name == '14_6':
  444. # ZT_H-GJT_SL_OD
  445. ai.init('{"func":"bzpj", "catagory":"14", "items":"6"}')
  446. params = {'viewport': {'type':'C', 'x':377, 'y':105, 'w':1997, 'h':1997}}
  447. if jpg_name == '14_10':
  448. # ZT_H-GJT_SL_CLS
  449. ai.init('{"func":"bzpj", "catagory":"14", "items":"10"}')
  450. params = {'viewport': {'type':'C', 'x':377, 'y':105, 'w':1997, 'h':1997}}
  451. # ------------------------------------------------------------------------------
  452. if jpg_name == '15_1':
  453. # ZT_QM-G_QH
  454. ai.init('{"func":"bzpj", "catagory":"15", "items":"1"}')
  455. params = {'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch}}
  456. if jpg_name == '15_2':
  457. # ZT_QM-G_DX
  458. ai.init('{"func":"bzpj", "catagory":"15", "items":"2"}')
  459. params = {'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch}}
  460. if jpg_name == '15_3':
  461. # ZT_QM-P_SL
  462. ai.init('{"func":"bzpj", "catagory":"15", "items":"3"}')
  463. params = {'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch}}
  464. if jpg_name == '15_4':
  465. # ZT_QM-F_SL
  466. ai.init('{"func":"bzpj", "catagory":"15", "items":"4"}')
  467. params = {'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch}}
  468. if jpg_name == '15_5':
  469. # ZT_QM-LGJ_SL
  470. ai.init('{"func":"bzpj", "catagory":"15", "items":"5"}')
  471. params = {'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch}}
  472. # ------------------------------------------------------------------------------
  473. if jpg_name == '16_1':
  474. # ZCG_GTG-QH
  475. ai.init('{"func":"bzpj", "catagory":"16", "items":"1"}')
  476. params = {'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch}}
  477. if jpg_name == '16_2':
  478. # ZCG_GTG-WZ_T
  479. ai.init('{"func":"bzpj", "catagory":"16", "items":"2"}')
  480. params = {'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch}}
  481. if jpg_name == '16_4':
  482. # ZCG_GTG-DZ
  483. ai.init('{"func":"bzpj", "catagory":"16", "items":"4"}')
  484. params = {
  485. 'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch},
  486. 'ZCG_GTG-DZ': {'direction':'v'}
  487. }
  488. # ------------------------------------------------------------------------------
  489. if jpg_name == '17_1':
  490. # YGXG-DZ_A
  491. ai.init('{"func":"bzpj", "catagory":"17", "items":"1"}')
  492. params = {'YGXG-DZ': {'direction':'h'}}
  493. if jpg_name == '17_4':
  494. # YGXG-DZ_D
  495. ai.init('{"func":"bzpj", "catagory":"17", "items":"4"}')
  496. params = {'YGXG-DZ': {'direction':'h'}}
  497. if jpg_name == '17_5':
  498. # YGXG-DZ_E
  499. ai.init('{"func":"bzpj", "catagory":"17", "items":"5"}')
  500. params = {
  501. 'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch},
  502. 'YGXG-DZ': {'direction':'v'}
  503. }
  504. # ------------------------------------------------------------------------------
  505. if jpg_name == '18_1':
  506. # YGB-JZW
  507. ai.init('{"func":"bzpj", "catagory":"18", "items":"1"}')
  508. params = {
  509. 'YGB-JZW': {'output_cls_names': ['a', 'b', 'c', 'd', 'ds'], 'direction':'h'},
  510. # 'input': [
  511. # {'shape_type':'line', 'shape_data':[(x1,y1),(x2,y2)], 'value':'A', 'action':'add'},
  512. # {'shape_type':'rect', 'shape_data':[(x1,y1),(x2,y2)], 'value':'D', 'action':'add'},
  513. # {'shape_type':'rect', 'shape_data':[(x1,y1),(x2,y2)], 'value':'', 'action':'delete'}
  514. # ]
  515. }
  516. if jpg_name == '18_2':
  517. # YGB-JLD_OD
  518. ai.init('{"func":"bzpj", "catagory":"18", "items":"2"}')
  519. if jpg_name == '18_10':
  520. # YGB-JLD_CLS
  521. ai.init('{"func":"bzpj", "catagory":"18", "items":"10"}')
  522. if jpg_name == '18_3':
  523. # YGB-W
  524. ai.init('{"func":"bzpj", "catagory":"18", "items":"3"}')
  525. params = {
  526. 'YBG-W': {'w_cls':'wa'},
  527. 'viewport': {'type':'C', 'x':cx, 'y':cy, 'w':cw, 'h':ch}
  528. }
  529. raw_msg = ai.do_pred_by_data(img, params)
  530. json_msg = json.loads(raw_msg.encode("utf-8"))
  531. detect_type = json_msg['content']['detect_type']
  532. title = json_msg['content']['title']
  533. details = json_msg['content']['details']
  534. print('')
  535. print('{}: {}'.format(jpg_name, json_msg['success']))
  536. if detect_type == 'zzsb':
  537. print('{}'.format(title))
  538. elif detect_type == 'bzpj':
  539. print('{}'.format(details))
  540. else:
  541. print('invalid detect_type={}'.format(detect_type))