PBL / Technology /project /basic1.py
shuai-zhao's picture
initial upload
7b6bf43 verified
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import math
import time
import __common
import wiringpi
from ultralytics import YOLO
import cv2
classall={
'apple': 1,
'shiliu': 1,
'shizi': 1,
'orange': 1,
'lemon': 2,
'strawberry': 2,
'avocado': 2,
'mango': 3,
'pear': 3,
'banana': 4}
def main():
#jstep_pos = [0, 0, 0, 0, 5 / 180.0 * math.pi, 0]
#jstep_neg = [0, 0, 0, 0, -5 / 180.0 * math.pi, 0]
initial_position=[0,0,math.pi/2,0,math.pi/2,math.pi/18]
down_pose=[0,0,-66,0,0,0]
down_pose1=[0,0,-160,0,0,0]#相对初始位置而言
up_pose=[0,0,66,0,0,0]
up_pose1=[0,0,94,0,0,0]
turning_pose=[218,-169,0,0,0,0]
#going_pose[0,-30,0,0,0,0]
going_pose=[0,-30,0,0,0,0]
rc = jkrc.RC("10.5.5.100")
print(rc.login())
print(rc.power_on())
print(rc.enable_robot())
#运动到初始位置
print('joint_move {}'.format(rc.joint_move(initial_position, 0, True, 0.8)))
ret=rc.linear_move(up_pose,1,True,50)
print(ret[0])
wiringpi.wiringPiSetup()
wiringpi.softPwmCreate(0,9,20)
wiringpi.softPwmWrite(0,9)
#识别程序
time.sleep(2)
model = YOLO("fruit.pt") # 加载训练好的 YOLO 模型
# 调用摄像头
cap = cv2.VideoCapture(0)
start_time=time.time()
timeout=5
if not cap.isOpened():
print("摄像头打开失败")
return
print("开始物体识别...")
result = None
while True:
ret, frame = cap.read()
if not ret:
print("摄像头读取失败")
break
# 使用 YOLO 模型进行预测
results = model.predict(frame) # YOLO 模型预测
for result in results:
classes = result.boxes.cls
class_names = [model.names[int(cls)] for cls in classes]
print(f"识别到物体: {class_names}")
break
# 显示摄像头画面
cv2.imshow("Camera", frame)
if time.time()-start_time>timeout: # 超时关闭
print("已关闭摄像头")
break
cap.release()
cv2.destroyAllWindows()
#识别以后:假设识别出来的结果变量名是result
allocate=classall[class_names[0]]
print("belong to"+str(allocate))
#下去抓:
ret=rc.linear_move(down_pose1,1,True,50)
print(ret[0])
front=[-50,0,0,0,0,0]
ret=rc.linear_move(front,1,True,50)
print(ret[0])
wiringpi.softPwmWrite(0,13)
ret=rc.linear_move(up_pose1,1,True,50)
print(ret[0])
ret=rc.linear_move(turning_pose,1,True,50)
print(ret[0])
for i in range(int(allocate)-1):
ret=rc.linear_move(going_pose,1,True,50)
print(ret[0])
ret=rc.linear_move(down_pose,1,True,50)
print(ret[0])
wiringpi.softPwmWrite(0,8)
print(rc.logout())
if __name__ == '__main__':
__common.init_env()
import jkrc
main()
# In[ ]: