coffee_linescan2(1time1000pic).py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import cv2
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import imutils
  5. from collections import defaultdict
  6. #import datetime
  7. #start = datetime.datetime.now()
  8. import time
  9. start = time.process_time()
  10. def makepic():
  11. count = 1000
  12. for x in range(count):
  13. img = np.ones((1,60),dtype=np.uint8)
  14. img[0,range(0,20)]=250
  15. img[0,range(20,40)]=30
  16. img[0,range(40,60)]=250
  17. filename = 'make' + str(x) + '.bmp'
  18. print(filename)
  19. cv2.imwrite(filename, img)
  20. def detectionpic():
  21. image = cv2.imread("make0.bmp")
  22. image2 = cv2.imread("make1.bmp")
  23. image_v = cv2.vconcat([image, image2]) # 垂直組合
  24. count = 998
  25. for x in range(count):
  26. # 讀取圖檔
  27. filename = 'make' + str(int(x * 1)) + '.bmp'
  28. print(filename)
  29. image = cv2.imread(filename)
  30. image_v = cv2.vconcat([image_v, image])
  31. cv2.imwrite("total.bmp", image_v)
  32. # 讀取圖檔
  33. filename = 'total.bmp'
  34. image = cv2.imread(filename)
  35. # 轉為灰階
  36. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  37. # 模糊化圖片
  38. blurred = cv2.GaussianBlur(gray, (11, 11), 0)
  39. cv2.imshow('Blur',blurred)
  40. cv2.waitKey(0)
  41. # Canny 尋找邊緣
  42. edged = cv2.Canny(blurred, 30, 150)
  43. cv2.imshow('Edged',edged)
  44. cv2.waitKey(0)
  45. # findContour 確定輪廓
  46. _,contours, hierarchy = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  47. img2 = image.copy()
  48. cv2.drawContours(img2, contours, -1, (0, 255, 0), 2)
  49. cv2.imshow('contour',img2)
  50. cv2.imwrite('check.bmp',img2)
  51. cv2.waitKey(0)
  52. cnt = contours[0]
  53. #contourArea 計算面積
  54. area = cv2.contourArea(cnt) #計算面積
  55. perimeter = cv2.arcLength(cnt,True) #計算周長
  56. if area < 19119:
  57. print('破損豆噴調',area)
  58. else:
  59. pass
  60. print('面積:',area, '周長:',perimeter) #印出結果
  61. '''
  62. p = 0
  63. d = 0
  64. tt = np.array(gray[0])
  65. print(tt)
  66. count = len(tt)
  67. print(len(tt))
  68. for i in tt[:]:
  69. if i >= 150:
  70. p = p + 1
  71. elif i <= 130:
  72. d = d + 1
  73. print('要得豆子像素:',p)
  74. print('壞的豆子像素:',d)
  75. coffeebean = (d / count)*100
  76. print('壞豆佔全部百分比:',coffeebean)
  77. if coffeebean > 60:
  78. record = record + 1
  79. print('紀錄次數:', record)
  80. else:
  81. pass
  82. if record == 50:
  83. j = 1
  84. # record=0
  85. print('噴嘴啟動')
  86. # break
  87. # continue
  88. '''
  89. #makepic()
  90. detectionpic()
  91. #end = datetime.datetime.now()
  92. #print("執行時間:", end - start)
  93. # 結束測量
  94. end = time.process_time()
  95. # 輸出結果
  96. print("執行時間:%f 秒" % (end - start))