You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.8 KiB

  1. import cv2
  2. import time
  3. import os
  4. import numpy as np
  5. import json
  6. vehicles = ["ambulance", "car1"]
  7. sides = [str(x) for x in range(0,361,30)]
  8. distances =["close_high","far_high","close_low","far_low"]
  9. def select_rect(im):
  10. rects=[]
  11. scale_percent = 100
  12. width = int(im.shape[1] * scale_percent / 100)
  13. height = int(im.shape[0] * scale_percent / 100)
  14. # Select ROI
  15. fromCenter = False
  16. r = cv2.selectROI(cv2.resize(im,(width,height)))
  17. # Crop image
  18. if(r == (0,0,0,0)):
  19. cv2.destroyAllWindows()
  20. imCrop = im[int(r[1]*100/scale_percent):int(r[1]*100/scale_percent+r[3]*100/scale_percent), int(r[0]*100/scale_percent):int(r[0]*100/scale_percent+r[2]*100/scale_percent)]
  21. # Display cropped image
  22. cv2.imshow("Image", imCrop)
  23. cv2.waitKey(0)
  24. cv2.destroyAllWindows()
  25. for i in r:
  26. rects.append(int(i)*int(100/scale_percent))
  27. print(rects)
  28. locs = {
  29. "x1": rects[0],
  30. "y1": rects[1],
  31. "x2": rects[0]+rects[2],
  32. "y2": rects[1]+rects[3],
  33. }
  34. return locs
  35. def take_image():
  36. cam_no = 0
  37. while 1:
  38. cam = cv2.VideoCapture(cam_no)
  39. if not (cam is None or not cam.isOpened()):
  40. break
  41. cam_no+=1
  42. for vehicle in vehicles:
  43. if vehicle == "ambulance":
  44. continue
  45. if not os.path.exists(vehicle):
  46. os.makedirs(vehicle)
  47. for distance in distances:
  48. for side in sides:
  49. for i in range(1,3):
  50. ret,img= cam.read()
  51. cv2.imwrite("{}/{}-{}({}).jpg".format(vehicle,distance,side,i),img)
  52. cv2.imshow("current",img)
  53. ex_c = [27, ord("q"), ord("Q")]
  54. if cv2.waitKey(1) & 0xFF in ex_c:
  55. break
  56. print("Took side {}:distance:{}, waiting 7 seconds".format(side,distance))
  57. time.sleep(7)
  58. print("Finished distance:"+distance)
  59. while not cv2.waitKey(1) & 0xFF in ex_c:
  60. ret,img= cam.read()
  61. cv2.imshow("current",img)
  62. print("Finished vehicle:"+vehicle)
  63. while not cv2.waitKey(1) & 0xFF in ex_c:
  64. ret,img= cam.read()
  65. cv2.imshow("current",img)
  66. def cut_image():
  67. cut_rects = {}
  68. for vehicle in vehicles:
  69. if not os.path.exists(vehicle):
  70. os.makedirs(vehicle)
  71. for distance in distances:
  72. for side in sides:
  73. img = cv2.imread("{}/{}-{}({}).jpg".format(vehicle,distance,side,1))
  74. cut_rects[vehicle + "-" + distance + "-" + side] = select_rect(img)
  75. cv2.destroyAllWindows()
  76. return cut_rects
  77. coordinates = cut_image()
  78. print(json.dumps(coordinates,indent=4))
  79. with open("coordinates.json","w") as file:
  80. file.write(json.dumps(coordinates,indent=4))