편집 기록

편집 기록
  • 프로필 nowp님의 편집
    날짜2023.09.18

    cv2 설치 오류 해결 방법 알려주실수 있나요?


    import serial
    import os
    import time
    import cv2
    import threading
    import numpy as np
    import smbus
    import RPi.GPIO as GPIO
    import speech_recognition as sr
    import pyaudio
    from openai import GPT3
    from gtts import gTTS
    from playsound import playsound
    from google.cloud import texttospeech
    from google.cloud import speech
    from google.cloud.speech import enums
    from google.cloud.speech import types
    
    # 카메라 모듈 설정
    def cameraa1():
        return cv2.VideoCapture(0)
    camera = cv2.VideoCapture(0)
    boxes = []
    idxs = []
    # 마이크 설정
    def mica1():
        return pyaudio.PyAudio()
    
    # 서보 모터 설정
    def servoa1(pin):
        GPIO.setup(pin, GPIO.OUT)
        return GPIO.PWM(pin, 50) # PWM with 50 Hz
    # 1 번 서보 모터 생성(핀 번호 17)
    servo1 = servoa1(17)
    # 2 번 서보 모터 생성(핀 번호 27)
    servo2 = servoa1(27)
    # 서보 모터 시작
    servo1.start(0)
    servo2.start(0)
    # 서보 모터 제어(예: 듀티 사이클을 50 % 로 변경)
    servo1.ChangeDutyCycle(50)
    servo2.ChangeDutyCycle(50)
    
    # DC 모터 설정
    def dcmotera1(pin):
        GPIO.setup(pin, GPIO.OUT)
        return GPIO.PWM(pin, 50) # PWM with 50 Hz
    # 1 번 DC 모터 생성(핀 번호 18)
    dc_motor1 = dcmotera1(18)
    # 2 번 DC 모터 생성(핀 번호 22)
    dc_motor2 = dcmotera1(22)
    # DC 모터 시작
    dc_motor1.start(0)
    dc_motor2.start(0)
    # DC 모터 제어(예: 듀티 사이클을 70 % 로 변경)
    dc_motor1.ChangeDutyCycle(70)
    dc_motor2.ChangeDutyCycle(70)
    
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
    
    lock = threading.Lock()
    text = r.recognize_google(audio, language='ko-KR')
    
    def get_audio():
        with sr.Microphone() as source:
            print("Listening...")
            audio = r.listen(source)
        said = ""
        try:
            said = r.recognize_google(audio, language = "ko-KR")
            print(said)
        except Exception as e:
            print("Exception: " + str(e))
        return said.lower()
    
    def play_sound1():
        # 소리 파일 재생 (당신이 원하는 소리 파일로 바꿔야 함)
        playsound('sound.wav')
    
    stop_command = False # stop_command 변수를 초기화
    
    def listen_for_command():
        r = sr.Recognizer()
        with sr.Microphone() as source:
            playsound('listening.wav')
            audio = r.listen(source)
            try:
                text = r.recognize_google(audio, language='ko-KR') # 한국어 음성 인식
                print(f"당신이 말한 것: {text}")
                return text
            except sr.UnknownValueError:
                playsound('fail.wav')
            except sr.RequestError as e:
                playsound('no internet.wav')
    
    def command_listener():
        global stop_command
        global gpt_running
    
        while True:
            if gpt_running:
                continue
    
            # 레코드
            print("Listening...")
            command = listen_for_command()
            if command:
                with lock:
                    if '멈춰' in command:
                        stop_command = True
    
                    if '로봇' in command:
                        if stop_command:
                            break
                        playsound2()
                        servo.start(0)
                        for i in range(0, 180, 2):
                            servo.ChangeDutyCycle(2.5 + 10 * i / 180)
                            time.sleep(0.02)
                        time.sleep(0.5)
                        servo.stop()
                        execute_command(command)
    
                if stop_command:
                    break
    
    def get_audio_and_stop():
        global stop_command
        r = sr.Recognizer()
        while True: # 지속적으로 듣기
            with sr.Microphone() as source:
                audio = r.listen(source)
                try:
                    text = r.recognize_google(audio, language='ko-KR') # 한국어 음성 인식
                    if '멈춰' in text: # '멈춰'라는 명령이 들어오면
                        stop_command = True # stop_command를 True로 설정
                        break # 멈추는 명령이 들어오면 오디오 청취를 중단
                except sr.UnknownValueError:
                    pass
                except sr.RequestError as e:
                    pass
            # 음성 인식이 일정 시간 간격으로 실행되도록 지연시킵니다.
            time.sleep(1)
    def speak(text):
        tts = gTTS(text = text, lang = 'ko') # 한국어로 변환
        filename = "voice.mp3"
        tts.save(filename)
        playsound(filename)
        os.remove(filename) # 파일을 재생한 후 삭제
    
    
    def follow_person():
        global stop_following, boxes, idxs
        # YOLO 알고리즘에 필요한 파일들
        # 실제 경로로 변경해야 합니다.
        labelsPath = "/home/korean.jeon/gdsb_python/yolo/coco.names"
        weightsPath = "/home/korean.jeon/gdsb_python/yolo/efficientnet_b0.pt"
        configPath = "/home/korean.jeon/gdsb_python/yolo/yolov5.cfg"
        # YOLO 라벨 불러오기
        LABELS = open(labelsPath).read().strip().split("\n")
        # YOLO 모델 불러오기
        net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
        # 적절한 출력 계층을 결정
        ln = net.getLayerNames()
        ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
    
        while True:
            # 프레임 읽기
            ret, frame = camera.read()
            if not ret:
                break
    
            (H, W) = frame.shape[:2]
            # YOLO를 통해 사람 탐지
            blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)
            net.setInput(blob)
            layerOutputs = net.forward(ln)
            boxes = []
            confidences = []
            classIDs = []
            for output in layerOutputs:
                for detection in output:
                    scores = detection[5:]
                    classID = np.argmax(scores)
                    confidence = scores[classID]
                    # 사람을 인식했는지 확인
                    if LABELS[classID] == "person" and confidence > 0.5:
                        box = detection[0:4] * np.array([W, H, W, H])
                        (centerX, centerY, width, height) = box.astype("int")
                        x = int(centerX - (width / 2))
                        y = int(centerY - (height / 2))
                        boxes.append([x, y, int(width), int(height)])
                        confidences.append(float(confidence))
                        classIDs.append(classID)
            # 겹치는 박스를 제거하기 위한 Non - Maximum Suppression(NMS) 을 사용
            idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.3)
            # 최소 한 개의 탐지가 있을 경우
            if len(idxs) > 0:
                for i in idxs.flatten():
                    # 탐지된 사람의 위치(x, y) = (boxes[i][0], boxes[i][1])
                    (w, h) = (boxes[i][2], boxes[i][3])
                    # 이 부분에서 로봇을 사람을 따라가도록 움직입니다.
                    pass
    
        camera.release()
        cv2.destroyAllWindows()
    
    def execute_command(command):
        global stop_command, gpt_running
        if "안녕" in text:
            playsound('hi.wav')
            servo.start(0)
            dc_motor.start(0)
            for i in range(0, 180, 2):
                if stop_command: # 멈추는 명령이 들어오면 동작을 중단
                    stop_command = False
                    break
                servo.ChangeDutyCycle(2.5 + 10 * i / 180) # 0 - 180 degree
                dc_motor.ChangeDutyCycle(2.5 + 10 * i / 180) # 0 - 180 degree
                time.sleep(0.02)
            time.sleep(0.5)
            servo.stop()
            dc_motor.stop()
        elif "시간" in text:
            speak(f"지금은 {time.ctime()}입니다.")
        elif "따라와" in text:
            playsound('yeser.wav')
            stop_command = False
            threading.Thread(target = get_audio_and_stop).start()
            threading.Thread(target=follow_person, args=(boxes, idxs)).start()  # follow_person 함수를 스레드로 실행
        elif "지피티 실행" in text:
            speak("지피티 실행")
            with lock:
                gpt_running = True
            run_gpt3()
        elif "지피티 중단" in text:
            with lock:
                gpt_running = False
    
    def run_gpt3():
        # GPT - 3 모델 초기화
        gpt = GPT3()
        # TTS 클라이언트 초기화
        tts_client = texttospeech.TextToSpeechClient()
        # STT 클라이언트 초기화
        stt_client = speech.SpeechClient()
        # 오디오 스트리밍 설정
        RATE = 16000
        CHUNK = int(RATE / 10) # 100 ms
        # 마이크 설정
        p = pyaudio.PyAudio()
        stream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK)
        # 음성 입력을 텍스트로 변환하는 함수
        def listen_print_loop(responses):
            for response in responses:
                if not response.results:
                    continue
                result = response.results[0]
                if not result.alternatives:
                    continue
                transcript = result.alternatives[0].transcript
                print("사용자: ", transcript)
                # GPT - 3 로 응답 생성
                response = gpt.generate_response(transcript)
                print("로봇: ", response)
                # 응답을 음성으로 변환
                synthesis_input = texttospeech.types.SynthesisInput(text=response)
                voice = texttospeech.types.VoiceSelectionParams(language_code='ko-KR', ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL)
                audio_config = texttospeech.types.AudioConfig(audio_encoding=texttospeech.enums.AudioEncoding.MP3)
                response = tts_client.synthesize_speech(synthesis_input, voice, audio_config)
                # 음성을 스피커로 출력
                with open('response.mp3', 'wb') as out:
                    out.write(response.audio_content)
                os.system("mpg321 response.mp3")
    
        def transcribe_streaming():
            config = speech.types.RecognitionConfig(
            encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16,
            sample_rate_hertz=16000,
            language_code='ko-KR')
            audio_generator = stream_generator()
            requests = (speech.StreamingRecognizeRequest(audio_content=content) for content in audio_generator)
            responses = stt_client.streaming_recognize(config, requests)
            listen_print_loop(responses)
    
        def stream_generator():
            while True:
                yield stream.read(CHUNK)
    
        transcribe_streaming()
        while gpt_running:  # GPT-3 가동 변수가 True로 설정되어 있는 동안 계속 실행합니다.
            run_gpt3()
            pass
    
    while True:  # 무한 루프를 통해 사용자의 명령을 계속 받습니다.
        if not gpt_running:  # 만약 GPT-3가 가동 중이 아니라면 명령을 계속 받습니다.
            command_listener()
    
    (cv_env) korean.jeon@raspberrypi:~/gdsb_python/opencv-4.5.3/build $ /home/korean.jeon/gdsb_python/cv_env/bin/python /home/korean.jeon/gdsb_python/debug.py
    Traceback (most recent call last):
      File "/home/korean.jeon/gdsb_python/debug.py", line 4, in <module>
        import cv2
      File "/home/korean.jeon/gdsb_python/cv_env/lib/python3.9/site-packages/cv2/__init__.py", line 181, in <module>
        bootstrap()
      File "/home/korean.jeon/gdsb_python/cv_env/lib/python3.9/site-packages/cv2/__init__.py", line 153, in bootstrap
        native_module = importlib.import_module("cv2")
      File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    ImportError: /home/korean.jeon/gdsb_python/cv_env/lib/python3.9/site-packages/cv2/cv2.abi3.so: undefined symbol: __atomic_store_8
    

    이 에러가 계속 뜨는데 해결방법을 알려주실수 있나요?

  • 프로필 전세계님의 편집
    날짜2023.09.05

    cv2 설치 오류 해결 방법 알려주실수 있나요?


    import serial import os import time import cv2 import threading import numpy as np import smbus import RPi.GPIO as GPIO import speech_recognition as sr import pyaudio from openai import GPT3 from gtts import gTTS from playsound import playsound from google.cloud import texttospeech from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types

    카메라 모듈 설정

    def cameraa1(): return cv2.VideoCapture(0) camera = cv2.VideoCapture(0) boxes = [] idxs = []

    마이크 설정

    def mica1(): return pyaudio.PyAudio()

    서보 모터 설정

    def servoa1(pin): GPIO.setup(pin, GPIO.OUT) return GPIO.PWM(pin, 50) # PWM with 50 Hz

    1 번 서보 모터 생성(핀 번호 17)

    servo1 = servoa1(17)

    2 번 서보 모터 생성(핀 번호 27)

    servo2 = servoa1(27)

    서보 모터 시작

    servo1.start(0) servo2.start(0)

    서보 모터 제어(예: 듀티 사이클을 50 % 로 변경)

    servo1.ChangeDutyCycle(50) servo2.ChangeDutyCycle(50)

    DC 모터 설정

    def dcmotera1(pin): GPIO.setup(pin, GPIO.OUT) return GPIO.PWM(pin, 50) # PWM with 50 Hz

    1 번 DC 모터 생성(핀 번호 18)

    dc_motor1 = dcmotera1(18)

    2 번 DC 모터 생성(핀 번호 22)

    dc_motor2 = dcmotera1(22)

    DC 모터 시작

    dc_motor1.start(0) dc_motor2.start(0)

    DC 모터 제어(예: 듀티 사이클을 70 % 로 변경)

    dc_motor1.ChangeDutyCycle(70) dc_motor2.ChangeDutyCycle(70)

    r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source)

    lock = threading.Lock() text = r.recognize_google(audio, language='ko-KR')

    def get_audio(): with sr.Microphone() as source: print("Listening...") audio = r.listen(source) said = "" try: said = r.recognize_google(audio, language = "ko-KR") print(said) except Exception as e: print("Exception: " + str(e)) return said.lower()

    def play_sound1(): # 소리 파일 재생 (당신이 원하는 소리 파일로 바꿔야 함) playsound('sound.wav')

    stop_command = False # stop_command 변수를 초기화

    def listen_for_command(): r = sr.Recognizer() with sr.Microphone() as source: playsound('listening.wav') audio = r.listen(source) try: text = r.recognize_google(audio, language='ko-KR') # 한국어 음성 인식 print(f"당신이 말한 것: {text}") return text except sr.UnknownValueError: playsound('fail.wav') except sr.RequestError as e: playsound('no internet.wav')

    def command_listener(): global stop_command global gpt_running

    while True:
        if gpt_running:
            continue
    
        # 레코드
        print("Listening...")
        command = listen_for_command()
        if command:
            with lock:
                if '멈춰' in command:
                    stop_command = True
    
                if '로봇' in command:
                    if stop_command:
                        break
                    playsound2()
                    servo.start(0)
                    for i in range(0, 180, 2):
                        servo.ChangeDutyCycle(2.5 + 10 * i / 180)
                        time.sleep(0.02)
                    time.sleep(0.5)
                    servo.stop()
                    execute_command(command)
    
            if stop_command:
                break
    

    def get_audio_and_stop(): global stop_command r = sr.Recognizer() while True: # 지속적으로 듣기 with sr.Microphone() as source: audio = r.listen(source) try: text = r.recognize_google(audio, language='ko-KR') # 한국어 음성 인식 if '멈춰' in text: # '멈춰'라는 명령이 들어오면 stop_command = True # stop_command를 True로 설정 break # 멈추는 명령이 들어오면 오디오 청취를 중단 except sr.UnknownValueError: pass except sr.RequestError as e: pass # 음성 인식이 일정 시간 간격으로 실행되도록 지연시킵니다. time.sleep(1) def speak(text): tts = gTTS(text = text, lang = 'ko') # 한국어로 변환 filename = "voice.mp3" tts.save(filename) playsound(filename) os.remove(filename) # 파일을 재생한 후 삭제

    def follow_person(): global stop_following, boxes, idxs # YOLO 알고리즘에 필요한 파일들 # 실제 경로로 변경해야 합니다. labelsPath = "/home/korean.jeon/gdsb_python/yolo/coco.names" weightsPath = "/home/korean.jeon/gdsb_python/yolo/efficientnet_b0.pt" configPath = "/home/korean.jeon/gdsb_python/yolo/yolov5.cfg" # YOLO 라벨 불러오기 LABELS = open(labelsPath).read().strip().split("\n") # YOLO 모델 불러오기 net = cv2.dnn.readNetFromDarknet(configPath, weightsPath) # 적절한 출력 계층을 결정 ln = net.getLayerNames() ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]

    while True:
        # 프레임 읽기
        ret, frame = camera.read()
        if not ret:
            break
    
        (H, W) = frame.shape[:2]
        # YOLO를 통해 사람 탐지
        blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416), swapRB=True, crop=False)
        net.setInput(blob)
        layerOutputs = net.forward(ln)
        boxes = []
        confidences = []
        classIDs = []
        for output in layerOutputs:
            for detection in output:
                scores = detection[5:]
                classID = np.argmax(scores)
                confidence = scores[classID]
                # 사람을 인식했는지 확인
                if LABELS[classID] == "person" and confidence > 0.5:
                    box = detection[0:4] * np.array([W, H, W, H])
                    (centerX, centerY, width, height) = box.astype("int")
                    x = int(centerX - (width / 2))
                    y = int(centerY - (height / 2))
                    boxes.append([x, y, int(width), int(height)])
                    confidences.append(float(confidence))
                    classIDs.append(classID)
        # 겹치는 박스를 제거하기 위한 Non - Maximum Suppression(NMS) 을 사용
        idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.3)
        # 최소 한 개의 탐지가 있을 경우
        if len(idxs) > 0:
            for i in idxs.flatten():
                # 탐지된 사람의 위치(x, y) = (boxes[i][0], boxes[i][1])
                (w, h) = (boxes[i][2], boxes[i][3])
                # 이 부분에서 로봇을 사람을 따라가도록 움직입니다.
                pass
    
    camera.release()
    cv2.destroyAllWindows()
    

    def execute_command(command): global stop_command, gpt_running if "안녕" in text: playsound('hi.wav') servo.start(0) dc_motor.start(0) for i in range(0, 180, 2): if stop_command: # 멈추는 명령이 들어오면 동작을 중단 stop_command = False break servo.ChangeDutyCycle(2.5 + 10 * i / 180) # 0 - 180 degree dc_motor.ChangeDutyCycle(2.5 + 10 * i / 180) # 0 - 180 degree time.sleep(0.02) time.sleep(0.5) servo.stop() dc_motor.stop() elif "시간" in text: speak(f"지금은 {time.ctime()}입니다.") elif "따라와" in text: playsound('yeser.wav') stop_command = False threading.Thread(target = get_audio_and_stop).start() threading.Thread(target=follow_person, args=(boxes, idxs)).start() # follow_person 함수를 스레드로 실행 elif "지피티 실행" in text: speak("지피티 실행") with lock: gpt_running = True run_gpt3() elif "지피티 중단" in text: with lock: gpt_running = False

    def run_gpt3(): # GPT - 3 모델 초기화 gpt = GPT3() # TTS 클라이언트 초기화 tts_client = texttospeech.TextToSpeechClient() # STT 클라이언트 초기화 stt_client = speech.SpeechClient() # 오디오 스트리밍 설정 RATE = 16000 CHUNK = int(RATE / 10) # 100 ms # 마이크 설정 p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK) # 음성 입력을 텍스트로 변환하는 함수 def listen_print_loop(responses): for response in responses: if not response.results: continue result = response.results[0] if not result.alternatives: continue transcript = result.alternatives[0].transcript print("사용자: ", transcript) # GPT - 3 로 응답 생성 response = gpt.generate_response(transcript) print("로봇: ", response) # 응답을 음성으로 변환 synthesis_input = texttospeech.types.SynthesisInput(text=response) voice = texttospeech.types.VoiceSelectionParams(language_code='ko-KR', ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL) audio_config = texttospeech.types.AudioConfig(audio_encoding=texttospeech.enums.AudioEncoding.MP3) response = tts_client.synthesize_speech(synthesis_input, voice, audio_config) # 음성을 스피커로 출력 with open('response.mp3', 'wb') as out: out.write(response.audio_content) os.system("mpg321 response.mp3")

    def transcribe_streaming():
        config = speech.types.RecognitionConfig(
        encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code='ko-KR')
        audio_generator = stream_generator()
        requests = (speech.StreamingRecognizeRequest(audio_content=content) for content in audio_generator)
        responses = stt_client.streaming_recognize(config, requests)
        listen_print_loop(responses)
    
    def stream_generator():
        while True:
            yield stream.read(CHUNK)
    
    transcribe_streaming()
    while gpt_running:  # GPT-3 가동 변수가 True로 설정되어 있는 동안 계속 실행합니다.
        run_gpt3()
        pass
    

    while True: # 무한 루프를 통해 사용자의 명령을 계속 받습니다. if not gpt_running: # 만약 GPT-3가 가동 중이 아니라면 명령을 계속 받습니다. command_listener()

    (cv_env) korean.jeon@raspberrypi:~/gdsb_python/opencv-4.5.3/build $ /home/korean.jeon/gdsb_python/cv_env/bin/python /home/korean.jeon/gdsb_python/debug.py Traceback (most recent call last): File "/home/korean.jeon/gdsb_python/debug.py", line 4, in import cv2 File "/home/korean.jeon/gdsb_python/cv_env/lib/python3.9/site-packages/cv2/init.py", line 181, in bootstrap() File "/home/korean.jeon/gdsb_python/cv_env/lib/python3.9/site-packages/cv2/init.py", line 153, in bootstrap native_module = importlib.import_module("cv2") File "/usr/lib/python3.9/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ImportError: /home/korean.jeon/gdsb_python/cv_env/lib/python3.9/site-packages/cv2/cv2.abi3.so: undefined symbol: __atomic_store_8

    이 에러가 계속 뜨는데 해결방법을 알려주실수 있나요?