当前位置:   article > 正文

python 智能识别 超市商品 python人工智能 图像识别可以检测图片,视频流,有界面_商品识别与检测系统

商品识别与检测系统

随着社会经济的发展,选择到超市购物的消费者越来越多,超市排长队付账的矛盾也越来越突出。对此,我们提出一种新型的购物车,通过识别商品录入同时放入购物车中,并利用检测系统检测是否与已知的商品信息相匹配,并把商品信息传送到显示屏上。实现人工智能识别超市商品商品

  1. import colorsys
  2. import os
  3. from timeit import default_timer as timer
  4. import time
  5. import numpy as np
  6. from keras import backend as K
  7. from keras.models import load_model
  8. from keras.layers import Input
  9. from PIL import Image, ImageFont, ImageDraw
  10. import cv2
  11. from yolo3.model import yolo_eval, yolo_body, tiny_yolo_body
  12. from yolo3.utils import letterbox_image
  13. class YOLO(object):
  14. def __init__(self):
  15. self.model_path = 'goods-train/yolov3.h5' # model path or trained weights path
  16. self.anchors_path = 'model_data/yolo_anchors.txt'
  17. self.classes_path = 'model_data/goods_classes.txt'
  18. self.score = 0.4
  19. self.iou = 0.45
  20. self.class_names = self._get_class()
  21. self.anchors = self._get_anchors()
  22. self.sess = K.get_session()
  23. self.model_image_size = (416, 416) # fixed size or (None, None), hw
  24. self.boxes, self.scores, self.classes = self.generate()
  25. def _get_class(self):
  26. classes_path = os.path.expanduser(self.classes_path)
  27. with open(classes_path) as f:
  28. class_names = f.readlines()
  29. class_names = [c.strip() for c in class_names]
  30. return class_names
  31. def _get_anchors(self):
  32. anchors_path = os.path.expanduser(self.anchors_path)
  33. with open(anchors_path) as f:
  34. anchors = f.readline()
  35. anchors = [float(x) for x in anchors.split(',')]
  36. return np.array(anchors).reshape(-1, 2)
  37. def generate(self):
  38. model_path = os.path.expanduser(self.model_path)
  39. assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'
  40. # Load model, or construct model and load weights.
  41. num_anchors = len(self.anchors)
  42. num_classes = len(self.class_names)
  43. is_tiny_version = num_anchors == 6 # default setting
  44. try:
  45. self.yolo_model = load_model(model_path, compile=False)
  46. except:
  47. self.yolo_model = tiny_yolo_body(Input(shape=(None, None, 3)), num_anchors // 2, num_classes) \
  48. if is_tiny_version else yolo_body(Input(shape=(None, None, 3)), num_anchors // 3, num_classes)
  49. self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match
  50. else:
  51. assert self.yolo_model.layers[-1].output_shape[-1] == \
  52. num_anchors / len(self.yolo_model.output) * (num_classes + 5), \
  53. 'Mismatch between model and given anchor and class sizes'
  54. print('{} model, anchors, and classes loaded.'.format(model_path))
  55. # Generate colors for drawing bounding boxes.
  56. hsv_tuples = [(x / len(self.class_names), 1., 1.)
  57. for x in range(len(self.class_names))]
  58. self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
  59. self.colors = list(
  60. map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
  61. self.colors))
  62. np.random.seed(10101) # Fixed seed for consistent colors across runs.
  63. np.random.shuffle(self.colors) # Shuffle colors to decorrelate adjacent classes.
  64. np.random.seed(None) # Reset seed to default.
  65. # Generate output tensor targets for filtered bounding boxes.
  66. self.input_image_shape = K.placeholder(shape=(2,))
  67. boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors,
  68. len(self.class_names), self.input_image_shape,
  69. score_threshold=self.score, iou_threshold=self.iou)
  70. return boxes, scores, classes
  71. def detect_image(self, image):
  72. if self.model_image_size != (None, None):
  73. assert self.model_image_size[0] % 32 == 0, 'Multiples of 32 required'
  74. assert self.model_image_size[1] % 32 == 0, 'Multiples of 32 required'
  75. boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))
  76. else:
  77. new_image_size = (image.width - (image.width % 32),
  78. image.height - (image.height % 32))
  79. boxed_image = letterbox_image(image, new_image_size)
  80. image_data = np.array(boxed_image, dtype='float32')
  81. # print(" image_data.shape:",image_data.shape)
  82. image_data /= 255.
  83. image_data = np.expand_dims(image_data, 0) # Add batch dimension.
  84. out_boxes, out_scores, out_classes = self.sess.run(
  85. [self.boxes, self.scores, self.classes],
  86. feed_dict={
  87. self.yolo_model.input: image_data,
  88. self.input_image_shape: [image.size[1], image.size[0]],
  89. K.learning_phase(): 0
  90. })
  91. font = ImageFont.truetype(font='font/FiraMono-Medium.otf',
  92. size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
  93. thickness = (image.size[0] + image.size[1]) // 300
  94. for i, c in reversed(list(enumerate(out_classes))):
  95. predicted_class = self.class_names[c]
  96. box = out_boxes[i]
  97. score = out_scores[i]
  98. label = '{} {:.2f}'.format(predicted_class, score)
  99. draw = ImageDraw.Draw(image)
  100. label_size = draw.textsize(label, font)
  101. top, left, bottom, right = box
  102. top = max(0, np.floor(top + 0.5).astype('int32'))
  103. left = max(0, np.floor(left + 0.5).astype('int32'))
  104. bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))
  105. right = min(image.size[0], np.floor(right + 0.5).astype('int32'))
  106. # print(label, (left, top), (right, bottom))
  107. center_y = (top + bottom) / 2
  108. center_x = (left + right) / 2
  109. if top - label_size[1] >= 0:
  110. text_origin = np.array([left, top - label_size[1]])
  111. else:
  112. text_origin = np.array([left, top + 1])
  113. # My kingdom for a good redistributable image drawing library.
  114. for i in range(thickness):
  115. draw.rectangle(
  116. [left + i, top + i, right - i, bottom - i],
  117. outline=self.colors[c])
  118. draw.point((center_x, center_y), fill=(255, 0, 0))
  119. draw.rectangle(
  120. [tuple(text_origin), tuple(text_origin + label_size)],
  121. fill=self.colors[c])
  122. draw.text(text_origin, label, fill=(0, 0, 0), font=font)
  123. del draw
  124. return image, len(out_classes)
  125. def close_session(self):
  126. self.sess.close()
  127. def detect_img(yolo):
  128. traindata_path = 'images'
  129. num_count = 0
  130. for img in os.listdir(traindata_path):
  131. print(img)
  132. try:
  133. image = Image.open(traindata_path + '/' + img)
  134. print("单幅图像", image.mode)
  135. except:
  136. print('Open Error! Try again!')
  137. else:
  138. r_image, num = yolo.detect_image(image)
  139. num_count = num_count + num
  140. result = np.asarray(r_image)
  141. result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
  142. cv2.imwrite('result/' + img, result)
  143. # r_image.show()
  144. yolo.close_session()
  145. print('-----------------')
  146. print('total images:%s' % len(os.listdir(traindata_path)))
  147. print('detect num:%s' % num_count)
  148. if __name__ == '__main__':
  149. detect_img(YOLO())

效果图:

效果视频:

python yolo超市商品识别

项目代码下载:

Python超市商品识别商品检测yolo可以检测图片,视频流,pyqt5有界面python商用源码-互联网文档类资源-CSDN下载Python超市商品识别商品检测yolo可以检测图片,视频流,有界面python商用源码参考视频:h更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/babyai996/27706411

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/298212
推荐阅读
相关标签
  

闽ICP备14008679号