1. 키보드 입력 감지 프로그램 (key1.py)
import cv2
import RPi.GPIO as gpio
import time
def main():
camera = cv2.VideoCapture(0)
camera.set(3, 640)
camera.set(4, 480)
if camera.isOpened() == False:
raise Exception("error")
while camera.isOpened():
key = cv2.waitKey(10)
if key != -1: # 키보드 입력이 없을 때는 -1이 반환된다.
print(key)
if key == ord('q'):
break
_, img = camera.read()
img = cv2.flip(img, -1)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
if __name__ == '__main__':
main()
2. 키보드 활살표를 누르면 감지하는 프로그램 (key2.py)
import cv2
import RPi.GPIO as gpio
import time
def main():
camera = cv2.VideoCapture(0)
camera.set(3, 640)
camera.set(4, 480)
if camera.isOpened() == False:
raise Exception("error")
while camera.isOpened():
key = cv2.waitKey(10)
if key == ord('q'):
break
elif key == 82:
print("up")
elif key == 84:
print("down")
elif key == 81:
print("left")
elif key == 83:
print("right")
_, img = camera.read()
img = cv2.flip(img, -1)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
if __name__ == '__main__':
main()
3. 키보드 입력으로 자동차를 움직여보자 (key3.py)
import cv2
import RPi.GPIO as gpio
import time
PWMA = 18
AIN1 = 22
AIN2 = 27
PWMB = 23
BIN1 = 25
BIN2 = 24
M = [18, 22, 27, 23, 25, 24]
gpio.setmode(gpio.BCM)
for i in M:
gpio.setup(M, gpio.OUT)
L_M = gpio.PWM(PWMA, 100)
L_M.start(0)
R_M = gpio.PWM(PWMB, 100)
R_M.start(0)
def drive(speed, left, right):
gpio.output(AIN1, left)
if left <= 0:
left2 = 1
else:
left2 = 0
gpio.output(AIN2, left2)
L_M.ChangeDutyCycle(speed)
gpio.output(BIN1, right)
if right <= 0:
right2 = 1
else:
right2 = 0
gpio.output(BIN2, right2)
R_M.ChangeDutyCycle(speed)
def main():
camera = cv2.VideoCapture(0)
camera.set(3, 640)
camera.set(4, 480)
if camera.isOpened() == False:
raise Exception("error")
while camera.isOpened():
key = cv2.waitKey(10) # 키보드를 누를 때 까지 기다리는 딜레이, 딜레이가 없으면 아래의 영상 출력 코드가 진행되지 않음.
if key == ord('q'):
break
elif key == 82:
print("up")
drive(50, 0, 0)
elif key == 84:
print("down")
drive(50, 1, 1)
elif key == 81:
print("left")
drive(50, 1, 0)
elif key == 83:
print("right")
drive(50, 0, 1)
elif key == 32: # 스페이스바 누를 시에 정지
print('stop')
drive(0, 0, 0)
_, img = camera.read()
img = cv2.flip(img, -1)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
if __name__ == '__main__':
main()
gpio.cleanup()
L_M.stop()
R_M.stop()
1. 필요한 영상 범위만 촬영하기 (dataV1.py)
import cv2
import RPi.GPIO as gpio
import time
def main():
camera = cv2.VideoCapture(0)
camera.set(3, 640)
camera.set(4, 480)
if camera.isOpened() == False:
raise Exception("error")
while camera.isOpened():
key = cv2.waitKey(10)
if key == ord('q'):
break
elif key == 82:
print("up")
elif key == 84:
print("down")
elif key == 81:
print("left")
elif key == 83:
print("right")
_, img = camera.read()
img = cv2.flip(img, -1)
cv2.imshow('img', img)
height, width, color = img.shape # 이미지의 세로(row) 사이즈와 가로(column) 사이즈 반환
save_img = img[int(height/2):,:,:] # row 값의 반절부터 끝까지 데이터 저장
cv2.imshow('save', save_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
if __name__ == '__main__':
main()
2. 딥러닝 학습 데이터에 유리한 RGB -> YUV 컬러 채널 변환 (dataV2.py)
import cv2
import RPi.GPIO as gpio
import time
def main():
camera = cv2.VideoCapture(0)
camera.set(3, 640)
camera.set(4, 480)
if camera.isOpened() == False:
raise Exception("error")
while camera.isOpened():
key = cv2.waitKey(10)
if key == ord('q'):
break
elif key == 82:
print("up")
elif key == 84:
print("down")
elif key == 81:
print("left")
elif key == 83:
print("right")
_, img = camera.read()
img = cv2.flip(img, -1)
# cv2.imshow('img', img)
height, width, color = img.shape # 이미지의 세로(row) 사이즈와 가로(column) 사이즈 반환
save_img = img[int(height/2):,:,:] # row 값의 반절부터 끝까지 데이터 저장
save_img = cv2.cvtColor(save_img, cv2.COLOR_BGR2YUV)
cv2.imshow('save', save_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
if __name__ == '__main__':
main()
3. 블러링 처리와 입력 shape 변경 (dataV3.py)
import cv2
import RPi.GPIO as gpio
import time
def main():
camera = cv2.VideoCapture(0)
camera.set(3, 640)
camera.set(4, 480)
if camera.isOpened() == False:
raise Exception("error")
while camera.isOpened():
key = cv2.waitKey(10)
if key == ord('q'):
break
elif key == 82:
print("up")
elif key == 84:
print("down")
elif key == 81:
print("left")
elif key == 83:
print("right")
_, img = camera.read()
img = cv2.flip(img, -1)
# cv2.imshow('img', img)
height, width, color= img.shape # 이미지의 세로(row) 사이즈와 가로(column) 사이즈 반환
save_img = img[int(height/2):] # row 값의 반절부터 끝까지 데이터 저장
save_img = cv2.cvtColor(save_img, cv2.COLOR_BGR2YUV)
save_img = cv2.GaussianBlur(save_img, (3,3), 0) # 블러링
save_img = cv2.resize(save_img, (200, 66)) # size 변환
cv2.imshow('save', save_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
if __name__ == '__main__':
main()
1. 캡쳐 이미지 저장하기 (dataSave1.py)
putty or VNC terminal
혹시 폴더를 잘못 만들었다면
import cv2
import RPi.GPIO as gpio
import time
def main():
camera = cv2.VideoCapture(0)
camera.set(3, 640)
camera.set(4, 480)
if camera.isOpened() == False:
raise Exception("error")
while camera.isOpened():
key = cv2.waitKey(10)
if key == ord('q'):
break
elif key == 82:
print("up")
elif key == 84:
print("down")
elif key == 81:
print("left")
elif key == 83:
print("right")
_, img = camera.read()
img = cv2.flip(img, -1)
# cv2.imshow('img', img)
height, width, color= img.shape
save_img = img[int(height/2):]
cv2.imshow('save', save_img)
cv2.imwrite("/home/pi/ai/video/test.png", save_img)
time.sleep(1.0) # 촬영 딜레이 만들어서 너무 많은 저장 방지하기
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
if __name__ == '__main__':
main()
cv2.imwrite(src, img)
2. 데이터 차곡차곡 쌓아가기 (dataSave2.py)
import cv2
import RPi.GPIO as gpio
import time
def main():
camera = cv2.VideoCapture(0)
camera.set(3, 640)
camera.set(4, 480)
filepath = '/home/pi/ai/video/test'
i = 0
if camera.isOpened() == False:
raise Exception("error")
while camera.isOpened():
key = cv2.waitKey(10)
if key == ord('q'):
break
elif key == 82:
print("up")
elif key == 84:
print("down")
elif key == 81:
print("left")
elif key == 83:
print("right")
_, img = camera.read()
img = cv2.flip(img, -1)
# cv2.imshow('img', img)
height, width, color= img.shape
save_img = img[int(height/2):]
cv2.imshow('save', save_img)
cv2.imwrite("%s_%05d.png" %(filepath, i), save_img)
i += 1
time.sleep(1.0) # 촬영 딜레이 만들어서 너무 많은 저장 방지하기
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
if __name__ == '__main__':
main()
필요없는 데이터 삭제하기
3. 필요에 따른 파일 라벨링 후 저장하기 (dataSave3.py)
import cv2
import RPi.GPIO as gpio
import time
def main():
camera = cv2.VideoCapture(0)
camera.set(3, 640)
camera.set(4, 480)
filepath = '/home/pi/ai/video/test'
i = 0
carState = 'stop' # 정지 상태
if camera.isOpened() == False:
raise Exception("error")
while camera.isOpened():
key = cv2.waitKey(10)
if key == ord('q'):
break
elif key == 82:
carState = 'go'
elif key == 84:
carState = 'back'
elif key == 81:
carState = 'left'
elif key == 83:
carState = 'right'
elif key == 32: # 스페이스바 누를 시에 정지
carState = 'stop'
print(carState)
_, img = camera.read()
img = cv2.flip(img, -1)
# cv2.imshow('img', img)
height, width, color= img.shape
save_img = img[int(height/2):]
save_img = cv2.cvtColor(save_img, cv2.COLOR_BGR2YUV)
save_img = cv2.GaussianBlur(save_img, (3,3), 0)
save_img = cv2.resize(save_img, (200, 66))
cv2.imshow('save', save_img)
if carState == "go":
cv2.imwrite("%s_%05d_%03d.png" %(filepath, i, 90), save_img) # 직진 90도
print("G")
i += 1
elif carState == "back":
cv2.imwrite("%s_%05d_%03d.png" %(filepath, i, 270), save_img) # 후진 270도
print("B")
i += 1
elif carState == "left":
cv2.imwrite("%s_%05d_%03d.png" %(filepath, i, 45), save_img) # 좌회전 45도
print("L")
i += 1
elif carState == "right":
cv2.imwrite("%s_%05d_%03d.png" %(filepath, i, 135), save_img) # 우회전 135도
print("R")
i += 1
elif carState == "stop":
# 정지 상태에서는 저장하지 않을 예정
print("S")
# time.sleep(1.0) # 많은 데이터가 필요하기 때문에 영상 저장 딜레이를 없앴다. 딜레이가 없으니 정말 빠르게 저장된다.
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
if __name__ == '__main__':
main()
4. 위에 만들어둔 조종기능과 합쳐 영상 획득 프로그램을 완성하자 (carSave4.py)
조종기능으로 이동하기
carSave4.py 코드로 이동하기
위 코드를 복사해서 조종기능 코드 위의 빈 셀에 붙여넣기 하면 이 코드로 바로 이동할 수 있는 링크를 생성할 수 있다.
import cv2
import RPi.GPIO as gpio
import time
PWMA = 18
AIN1 = 22
AIN2 = 27
PWMB = 23
BIN1 = 25
BIN2 = 24
M = [18, 22, 27, 23, 25, 24]
gpio.setmode(gpio.BCM)
for i in M:
gpio.setup(M, gpio.OUT)
L_M = gpio.PWM(PWMA, 100)
L_M.start(0)
R_M = gpio.PWM(PWMB, 100)
R_M.start(0)
def drive(speed, left, right):
gpio.output(AIN1, left)
if left <= 0:
left2 = 1
else:
left2 = 0
gpio.output(AIN2, left2)
L_M.ChangeDutyCycle(speed)
gpio.output(BIN1, right)
if right <= 0:
right2 = 1
else:
right2 = 0
gpio.output(BIN2, right2)
R_M.ChangeDutyCycle(speed)
def main():
camera = cv2.VideoCapture(0)
camera.set(3, 640)
camera.set(4, 480)
filepath = '/home/pi/ai/video/test'
i = 0
carState = 'stop' # 정지 상태
if camera.isOpened() == False:
raise Exception("error")
while camera.isOpened():
key = cv2.waitKey(10)
if key == ord('q'):
break
elif key == 82:
carState = 'go'
drive(50, 0, 0)
elif key == 84:
carState = 'back'
drive(50, 1, 1)
elif key == 81:
carState = 'left'
drive(50, 1, 0)
elif key == 83:
carState = 'right'
drive(50, 0, 1)
elif key == 32: # 스페이스바 누를 시에 정지
carState = 'stop'
drive(0, 0, 0)
print(carState)
_, img = camera.read()
img = cv2.flip(img, -1)
# cv2.imshow('img', img)
height, width, color= img.shape
save_img = img[int(height/2):]
save_img = cv2.cvtColor(save_img, cv2.COLOR_BGR2YUV)
save_img = cv2.GaussianBlur(save_img, (3,3), 0)
save_img = cv2.resize(save_img, (200, 66))
cv2.imshow('save', save_img)
if carState == "go":
cv2.imwrite("%s_%05d_%03d.png" %(filepath, i, 90), save_img) # 직진 90도
print("G")
i += 1
elif carState == "back":
cv2.imwrite("%s_%05d_%03d.png" %(filepath, i, 270), save_img) # 후진 270도
print("B")
i += 1
elif carState == "left":
cv2.imwrite("%s_%05d_%03d.png" %(filepath, i, 45), save_img) # 좌회전 45도
print("L")
i += 1
elif carState == "right":
cv2.imwrite("%s_%05d_%03d.png" %(filepath, i, 135), save_img) # 우회전 135도
print("R")
i += 1
elif carState == "stop":
# 정지 상태에서는 저장하지 않을 예정
print("S")
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
if __name__ == '__main__':
main()
gpio.cleanup()
데이터가 최대한 깔끔하게 나오도록 영상 데이터를 수정하면서 2000~3000의 데이터를 모아야 한다.
1. 파일 압축하기
putty 터미널
2. VNC 뷰어의 FTP 기능 사용하여 전송하기
3. 반대로 PC에서 라즈베리파이로 데이터 받아오기