본문 바로가기

파이썬(PYTHON)

컨베이어 움직임 DETECT

728x90

 
# conveyor 벨트 이미지 변경

import cv2
import numpy as np
import matplotlib.pyplot as plt
import glob
import os
from PIL import Image, ImageDraw, ImageFont
import pygame

def detect_lines(img, rho_a, theta_a):
    dst = img.copy()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    canny = cv2.Canny(gray, 50, 150, apertureSize=3, L2gradient=True)
    lines = cv2.HoughLines(canny, 1, np.pi / 180, 150, srn=100, stn=200, min_theta=0, max_theta=np.pi/2)
   
    f1_x1 = 300;f1_y1 = 1.4;f1_x2 = 340;f1_y2 = 1.54
    f1_ax = (f1_y2 - f1_y1) / (f1_x2 - f1_x1)
    f1_by = f1_y2 - (f1_ax * f1_x2)
   
    f2_x1 = 280;f2_y1 = 1.532;f2_x2 = 253;f2_y2 = 1.386
    f2_ax = (f2_y2 - f2_y1) / (f2_x2 - f2_x1)
    f2_by = f2_y2 - (f2_ax * f2_x2)
    #print('slope : ', a, 'y-axis : ', b)
    f1_x = np.linspace(200, 400, 100)
    f1_y = f1_ax * f1_x + f1_by
    f2_y = f2_ax * f1_x + f2_by
   
    for i in lines:
        rho, theta = i[0][0], i[0][1]
       
        f1_ans = f1_ax*rho + f1_by
        f2_ans = f2_ax*rho + f2_by
        #print(ans, theta)
        if f1_ans < theta and f2_ans > theta and rho > 280:
        #if 190 < rho and 1.38 < theta and ans <= theta:
        #if 0.8 < theta < 1.5:
            #print(rho, theta)
            rho_a = np.append(rho_a, rho)
            theta_a = np.append(theta_a, theta)
           
            a1, b1 = np.cos(theta), np.sin(theta)
            x0, y0 = a1*rho, b1*rho

            scale = img.shape[0] + img.shape[1]

            x1 = int(x0 + scale * -b1)
            y1 = int(y0 + scale * a1)
            x2 = int(x0 - scale * -b1)
            y2 = int(y0 - scale * a1)

            cv2.line(dst, (x1, y1), (x2, y2), (0, 255, 0), 2)
            print(x1, y1, x2, y2)
            break
        #cv2.circle(dst, (x0, y0), 3, (255, 0, 0), 5, cv2.FILLED)
    return dst, rho_a, theta_a, f1_x, f1_y, f2_y, rho, theta

cap = cv2.VideoCapture('PVC-conveyor-1.mp4')
fps = cap.get(cv2.CAP_PROP_FPS)
rho_a = []
theta_a = []
while cap.isOpened():
    ret, img = cap.read()
    img = cv2.resize(img, dsize=(640, 480))
    if ret:
        dst, rho_a, theta_a, f1_x, f1_y, f2_y, rho, theta = detect_lines(img, rho_a, theta_a)
        cv2.imshow('img', img)
       
        cv2.namedWindow('dst', cv2.WINDOW_GUI_NORMAL)
        cv2.imshow('dst', dst)
        cv2.waitKey(int(100/fps))
       
        plt.plot(rho_a, theta_a,'r.')
        plt.plot(rho, theta, 'b*')
        plt.plot(f1_x, f1_y)
        plt.plot(f1_x, f2_y)
        plt.xlim([275, 350])
        plt.ylim([1.3, 1.6])
        plt.pause(0.5)
        plt.clf()
    plt.savefig('result.png')
cap.release()
cv2.destroyAllWindows()

728x90