Error in my py code using multiple python files

时间:2017-05-16 09:28:40

标签: python opencv multiple-files

For a school project I need to write a python code in multiple files for a better organization.

I use Opencv 3.2.

I got a lot of pain to do it, in fact I got 2 uses of a program of ColorDetetion.

Here is my main

    # Set default logging handler to avoid "No handler found" warnings.
import logging
from DetectGreen import DetectGreen
from camera import Camera
import sys
from time import sleep
import threading
LOGGER = logging.getLogger(__name__)


class Main(object):

    camera = Camera()
    detectred = DetectGreen(hLower=0, uLower=0, vLower=0,
                            hUpper=255, uUpper=255, vUpper=255)

    detectgreen = DetectGreen(hLower=154, uLower=66, vLower=250,
                              hUpper=179, uUpper=132, vUpper=255)

    logging.basicConfig(level=logging.DEBUG,
                        format="%(levelname)s %(asctime)s [%(process)d] %(name)s %(filename)s:%(lineno)d %(message)s",
                        )

    def __init__(self):
        """Initialize MyClassManager instance."""
        LOGGER.debug("Create instance of MyClassManager")
        super(Main, self).__init__()
        self._worker = None
        LOGGER.info("End of init...")

    camera.start()
    sleep(5)
    detectred.start()
    detectgreen.start()

Here is my class for the camera, it works great:

import cv2
import numpy as np
import threading
from time import sleep
import logging

LOGGER = logging.getLogger(__name__)


class Camera(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.end = False
        self.ret = True
        self.frame = ["", ""]

    def run(self):
        self.instantiate()
        while not self.end:
            # Read image
            self.ret, self.frame = self.cam.read()
            cv2.imshow('frame', self.frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                self.end = True
                LOGGER.info("Clean before finish working...")

    def afficher(self):
        print("Resultat methode affichage")

    def instantiate(self):
        self.cam = cv2.VideoCapture(0)

Here is my colorDetection :

# Standard imports
import cv2
import numpy as np
import threading
from time import sleep
import logging
from camera import Camera

LOGGER = logging.getLogger(__name__)


class DetectGreen(threading.Thread):
    def __init__(self,
                 hLower, uLower, vLower,
                 hUpper, uUpper, vUpper):
        self._camera = Camera()
        threading.Thread.__init__(self)
        # self._stopper = threading.Event()
        LOGGER.info("Create thread DetectGreen")
        self._hLower = hLower
        self._hUpper = hUpper
        self._uLower = uLower
        self._uUpper = uUpper
        self._vLower = vLower
        self._vUpper = vUpper

    def run(self):
        mask = (0, 0, 0)
        end = False
        print("lancement")
        LOGGER.info("DetectGreen Start worker...")
        while not end:
            LOGGER.info("DetectGreen Working...")
            sleep(1)
            # Read image
            # cam = cv2.VideoCapture(0)

            while(1):
                if not self._camera.ret:
                    break

                canvas = self._camera.frame.copy()
                print("132")
                hsv = cv2.cvtColor(self._camera.frame, cv2.COLOR_BGR2HSV)
                lower = (self._hLower, self._uLower, self._vLower)  # 130,150,80
                upper = (self._hUpper, self._uUpper, self._vUpper)  # 250,250,120
                mask = cv2.inRange(hsv, lower, upper)
                mask = cv2.erode(mask, None, iterations=6)
                mask = cv2.dilate(mask, None, iterations=4)
                cv2.imshow('frame', self.frame)
                try:
                    # NB: using _ as the variable name for two of the outputs, as they're not used
                    _, contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
                    blob = max(contours, key=lambda el: cv2.contourArea(el))
                    M = cv2.moments(blob)
                    center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

                    cv2.circle(canvas, center, 10, (0, 0, 255), -1)
                except (ValueError, ZeroDivisionError):
                    pass

The color detection give my huge difficulty to "convert". I really don't know how I can use the copy() without make an error in the ColorDetection programm (self._camera.frame.copy()) give me the following error " 'list' object has no attribute 'copy' " which I understand but yes my frame is a mat, maybe I make a bad definition of it? Or there is threading issues?

DetectColor use the Camera and the main used to launch each tasks in the good order. I got 2 py files to integrate after those.

0 个答案:

没有答案