import cv2

import os


# 비디오 파일 경로

video_path = 'C:/Users/HP/Downloads/Best of Russian Driving Fails 2019.mp4'


# 비디오 파일 로드

cap = cv2.VideoCapture(video_path)


# 사용자가 제공한 분류기 파일의 경로

cascade_file_path = 'C:/Users/HP/Downloads/haarcascade_car.xml'


# 분류기 파일의 경로가 존재하는지 확인

if not os.path.isfile(cascade_file_path):

    print("Error: Cascade classifier file not found.")

    exit()


# 차량 검출을 위한 OpenCV의 기본적인 Classifier 로드

car_cascade = cv2.CascadeClassifier(cascade_file_path)


if not cap.isOpened():

    print("Error: Could not open video.")

    exit()


# 비디오 파일의 각 프레임에서 객체를 검출하여 표시

while cap.isOpened():

    ret, frame = cap.read()

    if not ret:

        print("End of video.")

        break


    # 그레이스케일 변환

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)


    # 차량 검출

    cars = car_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))


    # 차량 주위에 사각형 그리기

    for (x, y, w, h) in cars:

        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)


    # 결과 이미지 출력

    cv2.imshow('Vehicle Detection', frame)


    # 'q' 키를 누르면 종료

    if cv2.waitKey(1) & 0xFF == ord('q'):

        break


# 자원 해제

cap.release()

cv2.destroyAllWindows()



댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기
 
 
 

import serial

import numpy as np

import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation


# USB 시리얼 포트 설정

usb_port = 'COM5'  # 사용할 USB 포트 번호

baud_rate = 9600   # 통신 속도 (bps)


# 시리얼 포트 열기

ser = serial.Serial(usb_port, baud_rate)



# PID 제어 알고리즘 파라미터 설정

Kp = 0.5 # 비례 제어 게인

Ki = 0.2 # 적분 제어 게인

Kd = 0.1 # 미분 제어 게인

dt = 0.1  # 샘플링 간격



#Kp = [float(Kp)]  # 형변환 후 리스트로 정의

#Ki = [float(Ki)]

#Kd = [float(Kd)]

#dt = 0.1



#Kp = [0.1] # 비례 제어 게인

#Ki = [0.2]  # 적분 제어 게인

#Kd = [0.3]  # 미분 제어 게인

#dt = 0.1  # 샘플링 간격



# 목표 피드백 값 설정

target_feedback = 1


# 초기 PID 제어 변수 설정

integral = 0.1

prev_error = 1

derivative = 0.1




# 그래프 초기 설정

fig, ax = plt.subplots()

line_feedback, = ax.plot([], [], 'r-', label='Feedback')  # 피드백 데이터를 나타내는 선

line_control_signal, = ax.plot([], [], 'b-', label='Control Signal')  # 제어 신호 데이터를 나타내는 선

ax.set_ylim(0, 15)  # Y 축 범위 설정 (시리얼 데이터 범위에 따라 조정)

ax.set_xlim(0, 50)  # X 축 범위 설정


x_data = np.arange(0, 50)  # X 축 데이터 초기값 (0에서 100까지)

y_feedback = np.zeros(50)  # 피드백 데이터 초기값 (0으로 초기화)

y_control_signal = np.zeros(50)  # 제어 신호 데이터 초기값 (0으로 초기화)


# 그래프 초기 설정 적용

plt.xlabel('Time')

plt.ylabel('Value')

plt.title('Feedback Control with PID')

plt.legend()

plt.grid(True)



# 애니메이션 생성

def update(frame):

    global integral, prev_error


    # 시리얼 포트로부터 데이터 읽기

    received_data = ser.readline().decode().strip()


    # 데이터 출력 및 처리

    print("수신된 데이터:", received_data)


    if received_data:

        # 주어진 데이터 형식에 따라 데이터 처리 및 업데이트

        if 'Time' in received_data and 'Feedback' in received_data:

            # 주파수, 피드백 값 추출

            parts = received_data.split(', ')

            time = float(parts[0].split(': ')[1])

            feedback = float(parts[1].split(': ')[1])

            control_signal = float(parts[2].split(': ')[1])  # 제어 신호를 추출

            

            # 최근 100개 데이터 유지를 위해 데이터 이동

            y_feedback[:-1] = y_feedback[1:]

            y_control_signal[:-1] = y_control_signal[1:]


            # PID 제어 알고리즘 계산

            error = target_feedback - feedback

            integral += error * dt

            derivative = (error - prev_error) / dt

            control_signal = Kp * error + Ki * integral + Kd * derivative

            control_signal = max(control_signal, 0)


            # 최신 데이터 추가

            y_feedback[-1] = feedback

            y_control_signal[-1] = control_signal


            # 이전 오차 값 업데이트

            prev_error = error


            # 그래프 업데이트

            line_feedback.set_data(x_data, y_feedback)

            line_control_signal.set_data(x_data, y_control_signal)


    return line_feedback, line_control_signal


ani = FuncAnimation(fig, update, frames=50, interval=50, blit=True)


# 그래프 표시

plt.show()


# 프로그램 종료 시 시리얼 포트 닫기

ser.close()



댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기
 
 
 

import serial

import numpy as np

from djitellopy import Tello

import time

import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation


class KalmanFilter:

    def __init__(self, A, B, H, Q, R, x0, P0):

        self.A = A  # 시스템 모델 행렬

        self.B = B  # 제어 입력 행렬

        self.H = H  # 측정 모델 행렬

        self.Q = Q  # 프로세스 잡음 공분산 행렬

        self.R = R  # 측정 잡음 공분산 행렬

        self.x = x0  # 초기 상태 추정치

        self.P = P0  # 초기 오차 공분산 행렬


    def predict(self, u):

        # 예측 단계

        self.x = np.dot(self.A, self.x) + np.dot(self.B, u)

        self.P = np.dot(np.dot(self.A, self.P), self.A.T) + self.Q


    def update(self, z):

        # 업데이트 단계

        y = z - np.dot(self.H, self.x)

        S = np.dot(np.dot(self.H, self.P), self.H.T) + self.R

        K = np.dot(np.dot(self.P, self.H.T), np.linalg.inv(S))

        self.x = self.x + np.dot(K, y)

        self.P = self.P - np.dot(np.dot(K, self.H), self.P)


# 시스템 모델 파라미터

dt = 0.1  # 시간 간격

A = np.eye(3)  # 시스템 모델 행렬

B = np.eye(3) * dt  # 제어 입력 행렬

H = np.eye(3)  # 측정 모델 행렬

Q = np.eye(3) * 0.001  # 프로세스 잡음 공분산 행렬

R = np.eye(3) * 0.1  # 측정 잡음 공분산 행렬

x0 = np.zeros((3, 1))  # 초기 상태 추정치

P0 = np.eye(3)  # 초기 오차 공분산 행렬


# 시리얼 포트 설정

ser = serial.Serial('COM5', 9600)


# 칼만 필터 객체 생성

kf = KalmanFilter(A, B, H, Q, R, x0, P0)


# 제어 입력 설정 (PID 제어 알고리즘을 사용한다고 가정)

Kp = 0.1

Ki = 0.01

Kd = 0.05

setpoint = 10.0

initial_value = 0.0

dt = 0.1

total_time = 10.0

error_integral = np.zeros((3, 1))

prev_error = np.zeros((3, 1))


# Initialize lists to store data

time_data = []

feedback_data = []

control_data = []



while True:

    

    # 시리얼 데이터 수신

    data = ser.readline().decode().strip().split(',')

    print("Received data:", data)  # 데이터 확인


    # 데이터에서 유효한 값만 추출

    valid_data = [d.split(': ')[1] for d in data if ':' in d]

    print("Valid data:", valid_data)  # 추출된 데이터 확인


    # 필요한 만큼의 값을 부동 소수점으로 변환하여 사용

    roll, pitch, yaw = map(float, valid_data[:3])


    # 상태 벡터 설정

    z = np.array([[roll], [pitch], [yaw]])


    # 예측 단계

    kf.predict(np.zeros((3, 1)))  # 제어 입력은 0으로 가정


    # 업데이트 단계

    kf.update(z)


    # 상태 추정치

    estimated_roll, estimated_pitch, estimated_yaw = kf.x[0, 0], kf.x[1, 0], kf.x[2, 0]


    # PID 제어 알고리즘 적용

    roll_error = estimated_roll - roll

    pitch_error = estimated_pitch - pitch

    yaw_error = estimated_yaw - yaw


    roll_command = Kp * roll_error + Ki * error_integral[0, 0] + Kd * (roll_error - prev_error[0, 0])

    pitch_command = Kp * pitch_error + Ki * error_integral[1, 0] + Kd * (pitch_error - prev_error[1, 0])

    yaw_command = Kp * yaw_error + Ki * error_integral[2, 0] + Kd * (yaw_error - prev_error[2, 0])


    # 이전 오차 및 오차 적분 업데이트

    error_integral += np.array([[roll_error], [pitch_error], [yaw_error]])

    prev_error = np.array([[roll_error], [pitch_error], [yaw_error]])


    # 제어 출력 수행 (실제로는 드론에 명령을 보내는 코드가 여기에 위치할 것입니다)

    



    # 디버그 출력

    print("Estimated Roll:", estimated_roll)

    print("Estimated Pitch:", estimated_pitch)

    print("Estimated Yaw:", estimated_yaw)


class PID:

    def __init__(self, Kp, Ki, Kd, setpoint):

        self.Kp = Kp

        self.Ki = Ki

        self.Kd = Kd

        self.setpoint = setpoint

        self.prev_error = 0

        self.integral = 0


    def update(self, feedback_value):

        error = self.setpoint - feedback_value

        self.integral += error

        derivative = error - self.prev_error

        output = (self.Kp * error) + (self.Ki * self.integral) + (self.Kd * derivative)

        self.prev_error = error

        return output


# Simulation parameters

Kp = 1.0

Ki = 0.1

Kd = 0.05

setpoint = 10.0

initial_value = 0.0

dt = 0.1

total_time = 10.0


# Initialize lists to store data

time_data = []

feedback_data = []

control_data = []


# Initialize serial communication

ser = serial.Serial('COM5', 9600)  # Adjust the COM port as needed


# Simulate the PID controller

pid = PID(Kp, Ki, Kd, setpoint)

time = 0.0

feedback_value = initial_value


# Create a figure and axes for plotting

fig, ax = plt.subplots(2, 1)


while time < total_time:

    # Read data from serial port

    line = ser.readline().decode().strip()

    data = line.split(',')

    if len(data) == 3:

        time_data.append(float(data[0]))

        feedback_data.append(float(data[1]))

        control_data.append(float(data[2]))


        # Update feedback value

        feedback_value = feedback_data[-1]


        # Update control signal

        control_signal = pid.update(feedback_value)


        # Plot feedback value and control signal

        ax[0].plot(time_data, feedback_data, label='Feedback Value')

        ax[0].axhline(y=setpoint, color='r', linestyle='r-', label='Setpoint')

        ax[0].set_xlabel('Time')

        ax[0].set_ylabel('Feedback Value')

        ax[0].legend()


        ax[1].plot(time_data, control_data, label='Control Signal', color='g')

        ax[1].set_xlabel('Time')

        ax[1].set_ylabel('Control Signal')

        ax[1].legend()


        plt.pause(0.01)


        # Print current values

        print(f"Time: {time_data[-1]:.2f}, Feedback: {feedback_data[-1]:.2f}, Control Signal: {control_data[-1]:.2f}")


        time += dt


plt.show()





#데이터가 'edback: 1.15'와 같은 형식이라면 ':'를 기준으로 데이터를 분할하고

#필요한 부분을 추출할 수 있습니다. 이를 위해 다음과 같이 수정할 수 있습니다.



댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기
 
 
 

library(sp)

library(sf)

library(tidyr)

library(spatstat.sparse)

library(REdaS)

library(plotly)


co <- read.csv('d://kaggle/dataset_5/countries_of_the_world.csv')


df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')

df[,2] <- log(as.numeric(df[,2]))


co[,2] <- log(as.numeric(co[,2]))


elev <- read.csv("d://filebox/dataset_4/csv/elevp.csv")


qk <- read.csv('d://filebox/csv/earthquakes.csv')

qk[,2] <- log(as.numeric(qk[,2]))


deg2rad <- function(deg) {

  (deg * pi) / (180)

}


fig1 <- function(x,y){

  2*x+x+1=y

}


linear_fun<-function(x){

  4*x^2+2*x+1

}


nlat <- 100

nlon <- 100

lat <- seq(-180, 180, length.out = nlat)

lon <- seq(-90, 90, length.out = nlon)

lat <- matrix(rep(lat, nlon), nrow = nlat)

lon <- matrix(rep(lon, each = nlat), nrow = nlat)


LAND_ISO <- c("AUT","BEL","BGR","HRV","CYP","CZE","DNK","EST","FIN","FRA","DEU","GRC","HUN","IRL",

              "ITA","LVA","LTU","LUX","MLT","NLD","POL","PRT","ROU","SVK","SVN","ESP","SWE","GBR",

              "USA","CHN","KOR","JPN","EGY","ARE","JOR","SAU","AUS","KEN","NGA","BRA")

value <- runif(length(LAND_ISO), 1, 20)

df <- data.frame(LAND_ISO, value)


g <- list(

  projection = list(type = 'orthographic'),

  showland = TRUE,

  landcolor = toRGB("LightGrey"),

  showocean = TRUE,

  oceancolor = toRGB("LightBlue"),

  showlakes = TRUE,

  lakecolor = toRGB("Blue"),

  showrivers = TRUE,

  rivercolor = toRGB("Blue"),

  resolution = 100,

  showcountries = TRUE,

  countrycolor = toRGB("Black"),

  showlon = TRUE,

  loncolor = toRGB("White"),

  showlat = TRUE,

  latcolor = toRGB("White"),

  showcities = TRUE,

  citycolor = toRGB("Red"),

  showmark = TRUE,

  markcolor = toRGB("Green")

)


recruitment_info <- data.frame(Centre = c("CentreA", "CentreB", "CentreC"),

                               Lat = c(51.51770, 52.48947, 51.45451),

                               Long = c(-0.100400, -1.898575, -2.587910),

                               GroupA = c(907, 1910, 4419),

                               GroupB = c(47, 116, 277), stringsAsFactors = TRUE)


recruitment_info <- recruitment_info %>% 

  gather(Group, values, Centre, Lat, Long)


dat <- map_data(map = "world", region = "UK")


fig <- plot_geo(df, type = 'scattergeo', mode = 'lines') 


fig <- fig %>% 

  add_sf(

    data = sf::st_as_sf(maps::map("world", plot = TRUE, fill = TRUE)),

    x = ~ 1.001 * cos(deg2rad(x)) * cos(deg2rad(y)),

    y = ~ 1.001 * sin(deg2rad(x)) * cos(deg2rad(y)),

    z = ~ 1.001 * sin(deg2rad(y)),

    color = I("black"), size = I(1),

    hoverinfo = "skip"

  ) %>%

  add_surface(

    x = cos(deg2rad(lon)) * cos(deg2rad(lat)),

    y = sin(deg2rad(lon)) * cos(deg2rad(lat)),

    z = sin(deg2rad(lat)),

    surfacecolor = matrix(df$value, nrow = nlat, ncol = nlon),

    showscale = TRUE, hoverinfo = "skip",

    contours = list(

      x = list(highlight = TRUE),

      y = list(highlight = TRUE),

      z = list(highlight = TRUE)

    )) %>%

  add_trace(x = df$x, y = df$y, z = df$z, location = ~LAND_ISO,

            line = list(shape = "circle"), showlegend = TRUE,

            hoverinfo = "skip") %>%

  add_trace(

    z = ~value, locations = ~LAND_ISO,

    color = ~value, colors = 'Purples' ) %>%

  add_trace(

    type = "choroplethmapbox",

    geojson = paste(c(

      "https://gist.githubusercontent.com/cpsievert/",

      "7cdcb444fb2670bd2767d349379ae886/raw/",

      "cf5631bfd2e385891bb0a9788a179d7f023bf6c8/", 

      "us-states.json"

    ), collapse = ""),

    locations = row.names(state.x77),

    z = state.x77[, "Population"] / state.x77[, "Area"],

    span = I(0)

  ) %>%

  add_trace(

    type = "choroplethmapbox",

    geojson = paste(c("https://raw.githubusercontent.com/mlampros/DataSets/master/california.geojson"),

                    collapse = ""),

    locations = row.names(state.x77),

    z = state.x77[, "Population"] / state.x77[, "Area"],

    span = I(1)

  ) %>%

  add_segments(x = -cos(15), y = -180 ,xend = -360 ,yend = sin(45)) %>%

  add_segments(x = -100, xend = -50, y = 50, yend = 75) %>%

  layout(geo = g)


fig



댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기
 
 
 



댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기