query_insect.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import cv2
  2. import numpy as np
  3. import khandy
  4. from insectid import InsectDetector, InsectIdentifier
  5. detector = InsectDetector()
  6. identifier = InsectIdentifier()
  7. def query(img_file):
  8. insect_image = khandy.imread(img_file) # Read image
  9. if insect_image is None:
  10. print('Failed to read image.')
  11. if max(insect_image.shape[:2]) > 1280: # Resize image if it's too large
  12. insect_image = khandy.resize_image_long(insect_image, 1280)
  13. image_for_draw = insect_image.copy() # Copy image for drawing
  14. image_height, image_width = insect_image.shape[:2]
  15. boxes, confs, classes = detector.detect(insect_image)
  16. for box, conf, class_ind in zip(boxes, confs, classes): # Loop through all detected objects
  17. box = box.astype(np.int32)
  18. box_width = box[2] - box[0] + 1
  19. box_height = box[3] - box[1] + 1
  20. if box_width < 30 or box_height < 30:
  21. continue
  22. cropped = khandy.crop(insect_image, box[0], box[1], box[2], box[3])
  23. results = identifier.identify(cropped)
  24. print(results[0]) # 打印第一个结果,这里可以根据需要进行处理
  25. prob = results[0]['probability']
  26. if prob < 0.10:
  27. text = 'Unknown'
  28. else:
  29. text = '{}: {:.3f}'.format(results[0]['chinese_name'], results[0]['probability'])
  30. # 获取文本位置
  31. position = [box[0] + 2, box[1] - 20]
  32. position[0] = min(max(position[0], 0), image_width)
  33. position[1] = min(max(position[1], 0), image_height)
  34. # 画框
  35. cv2.rectangle(image_for_draw, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
  36. image_for_draw = khandy.draw_text(image_for_draw, text, position, font_size=15)
  37. return image_for_draw
  38. if __name__ == '__main__':
  39. image_file = 'images/七星瓢虫.jpg'
  40. image = query(image_file)
  41. # 保存图片到文件
  42. cv2.imwrite('images/query_result.jpg', image)