예제 #1
0
def test1():
    """Dummy-testing the external detector
    """
    width = 1920
    height = 1080

    analyzer = ExternalDetector(verbose=True,
                                debug=True,
                                executable=os.path.join(
                                    getModulePath(), "example_process1.py"),
                                image_dimensions=(width, height),
                                tmpfile="/tmp/valkka-debug")

    img = numpy.zeros((height, width, 3), dtype=numpy.uint8)

    for i in range(10):
        img[:, :, :] = i
        result = analyzer(img)
        # time.sleep(1)
        print("result =", result)

    analyzer.close()
예제 #2
0
class MVisionProcess(MVisionBaseProcess):
    """A multiprocess that uses stdin, stdout and the filesystem to communicate with an external machine vision program
    """
    name = "Stdin, stdout and filesystem example"
    tag = "nix"
    auto_menu = True  # append automatically to valkka live machine vision menu or not
    max_instances = 3

    # The (example) process that gets executed.  You can find it in the module directory
    executable = "python3 " + os.path.join(getModulePath(),
                                           "example_process1.py")

    # For each outgoing signal, create a Qt signal with the same name.  The
    # frontend Qt thread will read processes communication pipe and emit these
    # signals.
    #"""
    class Signals(QtCore.QObject):
        pong = Signal(object)
        shmem_server = Signal(
            object
        )  # launched when the mvision process has established a shared mem server
        text = Signal(object)

    #"""

    parameter_defs = {"verbose": (bool, False)}

    def __init__(self, name="MVisionProcess", **kwargs):
        parameterInitCheck(self.parameter_defs, kwargs, self)
        super().__init__(name=name)
        self.analyzer = None

    def preRun_(self):
        super().preRun_()
        self.analyzer = None

    def postRun_(self):
        if (self.analyzer): self.analyzer.close()
        super().postRun_()  # calls deactivate_ => preDeactivate

    def postActivate_(self):
        """Create temporary file for image dumps and the analyzer itself
        """
        super().postActivate_()
        self.tmpfile = os.path.join(
            constant.tmpdir,
            "valkka-" + str(os.getpid()))  # e.g. "/tmp/valkka-10968"
        self.analyzer = ExternalDetector(
            executable=self.executable,
            image_dimensions=self.image_dimensions,
            tmpfile=self.tmpfile,
            verbose=self.verbose)

    def preDeactivate_(self):
        """Whatever you need to do prior to deactivating the shmem client
        """
        super().preDeactivate_()
        if (self.analyzer): self.analyzer.close()
        self.analyzer = None

    def cycle_(self):
        # NOTE: enable this to see if your multiprocess is alive
        self.logger.info("cycle_ starts")
        """
        index, isize = self.client.pull()
        if (index is None):
            self.logger.info("Client timed out..")
            pass
        else:
            self.logger.info("Client index, size =",index, isize)
            data = self.client.shmem_list[index]
            img = data.reshape(
                (self.image_dimensions[1], self.image_dimensions[0], 3))
            result = self.analyzer(img)
        """
        index, meta = self.client.pullFrame()
        if (index is None):
            self.logger.debug("Client timed out..")
            return

        self.logger.debug("Client index = %s", index)
        if meta.size < 1:
            return

        data = self.client.shmem_list[index][0:meta.size]
        img = data.reshape((meta.height, meta.width, 3))
        self.logger.debug("got frame %s", img.shape)
        result = self.analyzer(img)  # does something .. returns something ..

        if self.qt_server is not None:
            self.logger.info("pushing frame to server")
            self.qt_server.pushFrame(img, meta.slot, meta.mstimestamp)

        if (result != ""):
            self.send_out__(MessageObject("text", message=result))
            # self.sendSignal_(name="text", message=result)

    # *** create a widget for this machine vision module ***
    def getWidget(self):
        widget = QtWidgets.QLabel("NO TEXT YET")
        widget.setStyleSheet(style.detector_test)
        self.signals.text.connect(lambda message_object:\
            widget.setText(message_object["message"]))
        return widget
예제 #3
0
class MVisionProcess(QValkkaShmemProcess2):
    """A multiprocess that uses stdin, stdout and the filesystem to communicate with an external machine vision program
    """
    name = "Stdin, stdout and filesystem example"
    tag = "nix"
    max_instances = 3

    # The (example) process that gets executed.  You can find it in the module directory
    executable = "python3 " + os.path.join(tools.getModulePath(),
                                           "example_process1.py")

    incoming_signal_defs = {  # each key corresponds to a front- and backend method
        # don't touch these three..
        "activate_": {
            "n_buffer": int,
            "image_dimensions": tuple,
            "shmem_name": str
        },
        "deactivate_": [],
        "stop_": []
    }

    outgoing_signal_defs = {"text": {"message": str}}

    # For each outgoing signal, create a Qt signal with the same name.  The
    # frontend Qt thread will read processes communication pipe and emit these
    # signals.
    #"""
    class Signals(QtCore.QObject):
        text = QtCore.Signal(object)

    #"""

    parameter_defs = {"verbose": (bool, False)}

    def __init__(self, **kwargs):
        parameterInitCheck(self.parameter_defs, kwargs, self)
        super().__init__(self.__class__.name)
        self.pre = self.__class__.__name__ + ":" + self.name + " : "
        self.signals = self.Signals()

    def preRun_(self):
        self.analyzer = None
        super().preRun_()  # calls deactivate_ => preDeactivate_

    def postRun_(self):
        if (self.analyzer): self.analyzer.close()
        super().postRun_()  # calls deactivate_ => preDeactivate

    def postActivate_(self):
        """Create temporary file for image dumps and the analyzer itself
        """
        self.tmpfile = os.path.join(
            constant.tmpdir,
            "valkka-" + str(os.getpid()))  # e.g. "/tmp/valkka-10968"
        self.analyzer = ExternalDetector(
            executable=self.executable,
            image_dimensions=self.image_dimensions,
            tmpfile=self.tmpfile)

    def preDeactivate_(self):
        """Whatever you need to do prior to deactivating the shmem client
        """
        if (self.analyzer): self.analyzer.close()
        self.analyzer = None

    def cycle_(self):
        # NOTE: enable this to see if your multiprocess is alive
        self.report("cycle_ starts")
        index, isize = self.client.pull()
        if (index is None):
            self.report("Client timed out..")
            pass
        else:
            self.report("Client index, size =", index, isize)
            data = self.client.shmem_list[index]
            img = data.reshape(
                (self.image_dimensions[1], self.image_dimensions[0], 3))
            result = self.analyzer(img)

            if (result != ""):
                self.sendSignal_(name="text", message=result)

    # *** backend methods corresponding to incoming signals ***
    # *** i.e., how the signals are handled inside the running multiprocess

    def stop_(self):
        self.running = False

    # ** frontend methods launching incoming signals
    # *** you can call these after the multiprocess is started

    def stop(self):
        self.sendSignal(name="stop_")

    # ** frontend methods handling outgoing signals ***

    def text(self, message=""):
        self.report("At frontend: text got message", message)
        self.signals.text.emit(message + "\n")

    # *** create a widget for this machine vision module ***
    def getWidget(self):
        widget = QtWidgets.QLabel("NO TEXT YET")
        widget.setStyleSheet(style.detector_test)
        self.signals.text.connect(lambda message: widget.setText(message))
        return widget