写出python通过opencv调用摄像头实现米粒计数的代码
时间: 2023-10-23 22:10:58 浏览: 90
Sure, here is an example code that uses OpenCV to count rice grains in an image captured from a camera:
```
import cv2
cap = cv2.VideoCapture(0) # open default camera
while True:
ret, frame = cap.read() # get a frame from the camera
# apply some image processing operations to highlight rice grains
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 160, 255, cv2.THRESH_BINARY)[1]
eroded = cv2.erode(thresh, (5,5), iterations=5)
cnts = cv2.findContours(eroded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
# draw a bounding box around each rice grain and count them
count = 0
for c in cnts:
area = cv2.contourArea(c)
if area > 50:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)
count += 1
# show the image with rice grains and count
cv2.putText(frame, "Count: {}".format(count), (10,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
cv2.imshow("Rice Grains Counter", frame)
# exit when 'q' key is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
This code captures frames from the default camera, applies some image processing
阅读全文