我修改了我的代码是:您可以在函数get_angle中看到我如何在while循环中添加“ iMshow”和“打印(未找到的质量中心”)。我希望这张图片会出现一秒钟,丝网印刷“未找到的质量中心”的消息,因为我只是拍了墙的照片,并且图片中没有蓝色点。
from picamera2 import Picamera2 import cv2 import numpy as np import time import math import argparse import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) PWM_pin = 32 #Define pin, frequency and duty cycle freq = 50 dutyCycle = 7.5 #90 degrees at first# #Values 0 - 100 (represents 4%, ~27 deg) GPIO.setup(PWM_pin, GPIO.OUT) # Create PWM instance for pin w freqency pwm = GPIO.PWM(PWM_pin, freq) picam2 = Picamera2() parser=argparse.ArgumentParser(description="lower and upper bound for trying") parser.add_argument('--tim',default=10,help="length of time to run") parser.add_argument('--delay',default=0.5,help="time between image captures") parser.add_argument('--debug',action='store_true',default=False,help="debug mode") args=parser.parse_args() def get_duty(direction) duty=(1/18)*direction +2.5 return duty def get_angle(img,debug): hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, (90, 20, 130), (110, 255, 255)) cv2.imwrite('masked.jpg', mask) M = cv2.moments(mask) cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) if M['m00']==0: angle=360 print('no center of mass found') else: img_2=img.copy() img_2 = cv2.circle(img_2, (cX,cY), 5, (0,0,255), 2) # red circle placed on the center of mass cv2.imwrite('center_of_mass.jpg', img_2) angle=180/math.pi*(math.atan((cX-0.5*img.shape[1])/(img.shape[0]-cY))) #calculate angle of reference print(f'''angle in degree {angle:0.2f}''') if debug== True: print(f'center of mass:({cX},{cY})') cv2.imshow("masked",mask) cv2.imshow("center_of_mass",img_2) cv2.waitKey(1000) cv2.destroyAllWindows() return angle start_time=time.time() now_time=time.time() while now_time-start_time<args.tim: img_RAM = picam2.capture_array("main") #take picture into memory cv2.imshow("picture",img_RAM) cv2.waitKey(1000) cv2.destroyAllWindows() # debug=args.debug # # img_test = cv2.imread("bluetape.jpg") # angle=get_angle(img_RAM,debug) #call function # if -91 <angle< 91: # real_angle= angle+90 #real angle from horizontal # dutyCycle=get_duty(real_angle) # pwm.ChangeDutyCycle(dutyCycle) # if debug ==True: # print(f'PWM:{dutyCycle}') # else: # pass now_time=time.time() time.sleep(args.delay)'''
足够,它没有打印出任何东西,也没有显示图片。另外,它不会在10s之后自动结束。
解决,忘记放置picam2.start()。它应该放在段循环的开始时。