我一直試圖在啓動時運行在樹莓派下面的代碼:在啓動時運行的腳本不記錄輸出
#!/usr/bin/python3
import numpy
import math
import cv2
#this is python 3 specific
import urllib.request
from enum import Enum
from VisionProcessor import VisionProcessor
from GripPipeline import GripPipeline
from networktables import NetworkTables
import time
import logging
from networktables.util import ntproperty
#proper networktables setup
logging.basicConfig(level=logging.DEBUG)
NetworkTables.initialize(server='10.17.11.76')
#create the field to talk to on the network table
class NTClient(object):
angle_difference = ntproperty('/Raspberry Pi/angle difference', 0)
distance_from_target = ntproperty('/Raspberry Pi/distance from target', 0)
n = NTClient()
frame = cv2.VideoCapture('https://frc:[email protected]/mjpg/video.mjpg')
if(frame == None):
print("error: camera not found. check connection")
#pipeline = GripPipeline()
pipeline = VisionProcessor()
print("pipeline created")
def get_image():
ret, img_array = frame.read()
# cv2.imwrite("frame.jpg", img_array)
return img_array
def find_distance(width, height, y):
#distances are in inches
KNOWN_WIDTH = 6.25
KNOWN_DISTANCE = 12.0
KNOWN_PIXELS = 135.5
KNOWN_HEIGHT = 424.0
focal_length = (KNOWN_PIXELS * KNOWN_DISTANCE)/KNOWN_WIDTH
#hypotenuse = (KNOWN_WIDTH * focal_length)/width
distance = (KNOWN_WIDTH * focal_length)/width
#0.2125 degrees per pixel vertical
# theta = (0.2125) * (240 - y)
# distance = KNOWN_HEIGHT * (math.tan((math.pi/2) - math.radians(theta)))
return distance
x = True
while x:
print("while loop entered")
img = get_image()
print("image gotten")
center_point = [160, 120]
file = open('output.txt', 'a')
try:
current_point, size, y = pipeline.process(img)
#negative means turn left, positive means turn right
pixel_difference = center_point[0] - current_point[0]
#4.7761 pixels per degree
angle_difference = (float)(pixel_difference)/4.7761
n.angle_difference = angle_difference
target_width = size[0]
target_height = size[1]
distance = find_distance(target_width, target_height, y)
n.distance_from_target = distance
print("angle")
file.write("angle: ")
print(n.angle_difference)
file.write(str(angle_difference))
print(" distance: ")
file.write("distance")
print(distance)
file.write(str(distance))
file.write("\n")
except UnboundLocalError:
print(":(")
except (TypeError, cv2.error) as e:
print(":(")
# x = False
我已經通過編輯/etc/rc.local
文件這樣做,和腳本已成功運行。 Pi在啓動時顯示約25%的CPU使用率,並且在腳本運行時保持一致,所以我可以看到它何時處於活動狀態(我沒有在此Pi上運行任何其他進程)。使用ps -aux
顯示活動的python3進程。但是,它不會輸出任何內容,或者輸出到output.txt
文件或網絡表。
我的最終目標是讓它成功輸出到網絡表。如果我正常運行它(例如,不在啓動時,通過終端中的python3 pipeline-test.py
),它會正確輸出到output.txt
和網絡表。我添加了output.txt
作爲確保我獲得正確輸出的一種方式,除了在啓動時運行時,它工作得很好。
有沒有人有什麼可能是錯的想法?如果需要更多信息,我可以盡我所能提供。
編輯:出於某種原因,當我從Github複製我的代碼時,它失去了所有的縮進。正在使用的代碼是here。
這將有助於如果有問題的代碼被正確地縮進。 – martineau
@martineau對不起,我把它從我的Github中複製出來,出於某種原因,縮進沒有結束。我修復了它。縮進在正在運行的位置是正確的。 –
爲什麼你的循環中有'open'語句?您一遍又一遍地打開文件。它應該在循環之外,可能你應該看看使用'with open' ...「模式。你的縮進還沒有結束......你的除了需要與你的嘗試相同的水平。 – RobertB