본문 바로가기

파이썬(PYTHON)

컨베이어 원료 인식

728x90
# 원근 변화
# conveyor 벨트 이미지 변경

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


cou_e = 0
cou_ee = []
cou_n = 0
cou_nn = []
k1 = 25
k2 = 25
   
while True:
    font = cv2.FONT_HERSHEY_DUPLEX
    ss = []
    cap = cv2.VideoCapture('PVC-conveyor-1.mp4')

    while cap.isOpened():
        ret, img = cap.read()
        if ret:
            #pts = np.float32([[358, 200], [358, 450], [390, 200], [390, 450]])
            pts = np.float32([[286, 170], [282, 430], [302, 170], [306, 430]])

           
            # 좌상 , 좌하, 우상, 우하 위치 좌표
            pts_dst = np.float32([[0, 0], [0, 300], [300, 0], [300, 300]])
           
            M_1 = cv2.getPerspectiveTransform(pts, pts_dst)
            dst = cv2.warpPerspective(img, M_1, (300, 300))
           
            dst_gray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)
            ret, thresh1 = cv2.threshold(dst_gray, 127, 255, cv2.THRESH_BINARY_INV)
           
            contours, hierachy = cv2.findContours(thresh1, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
           
            #print(hierachy)
            try:
                for contour in range(contours):
                    thresh1 = cv2.drawContours(thresh1, [contour], -1, (0, 0, 255), 2)
            except:
                pass
           
            ss = sum(sum(thresh1 > 127))
           
            if ss < 41500:
                cou_e += 1
                cou_n = 0
                cv2.putText(img, 'EXIST', (220, 90), font, 2,(0,255,0), 2, cv2.LINE_AA)
                cv2.putText(img, str(cou_e), (280, 440), font, 2,(0,255,0), 2, cv2.LINE_AA)
                if cou_e != 0:
                    cou_ee = np.append(cou_ee, cou_e)
            else:
                cou_n += 1
                cou_e = 0
                cv2.putText(img, 'NON-EXIST', (120, 90), font, 2,(0,0,255), 2, cv2.LINE_AA)
                cv2.putText(img, str(cou_n), (260, 440), font, 2,(0,0,255), 2, cv2.LINE_AA)
                if cou_n != 0:
                    cou_nn = np.append(cou_nn, cou_n)
           
            try:    
                print('cou_ee : ', np.max(cou_ee))
                k1 = np.max(cou_ee)+2
                print('cou_nn : ', np.max(cou_nn))
                k2 = np.max(cou_nn)+2
                print(' ')
               
            except:
                pass
           
            img[170:430, 284, 1] = 255
            img[170:430, 304, 1] = 255
           
            if cou_n > k1 or cou_e > k2:
                img[:,:,:] = 0

            cv2.imshow('img', img)
            cv2.imshow('dst', dst)
            cv2.imshow('dst_gray', dst_gray)
            cv2.imshow('thresh1', thresh1)

            cv2.waitKey(300)
    cap.release()
    cv2.destroyAllWindows()


728x90