Python:多进程运行问题OPENCV&覆盆子皮

时间:2017-09-12 11:44:33

标签: python opencv raspberry-pi systemd

这是我在Raspberry Pi 3+上玩的源代码。

#!/usr/bin/env python

import cv2
import numpy as np
import time
import count_helper
from imutils.video import VideoStream
from sort import *
import argparse
import ConfigParser
import MySQLdb
import datetime


# Creating Connection

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="root",         # your username
                     passwd="root",  # your password
                     db="peoplecount")        # name of the data base

# Creating Cursor
cur = db.cursor()


config = ConfigParser.RawConfigParser()
config.read('config.cfg')

# FULL URL
url_full = '{}/api/peoplecount/'.format(config.get('server', 'url'))
parser = argparse.ArgumentParser()
parser.add_argument("--video", type=str)
parser.add_argument("--display", type=str)
parser.add_argument("--numline", type=str, default="single")
args = parser.parse_args()
starttime = time.time()

mot_tracker = Sort()
if args.video == "picam":
    c = VideoStream(usePiCamera=1, resolution=(640, 480)).start()
    time.sleep(2.0)
    f = c.read()
    f = cv2.resize(f, (400, 300))
elif args.video == "cam":
    c = cv2.VideoCapture(0)
    ret, f = c.read()
    f = cv2.resize(f, (400, 300))
else:
    c = cv2.VideoCapture(args.video)
    ret, f = c.read()
    f = cv2.resize(f, (400, 300))

width = int(f.shape[1])
height = int(f.shape[0])
bgs_mog = cv2.createBackgroundSubtractorMOG2()

kernelOp = np.ones((3, 3), np.uint8)
kernelCl = np.ones((11, 11), np.uint8)

y1 = config.getint('Line', 'y1')
y2 = config.getint('Line', 'y2')


entry_disp = 0
exit_disp = 0

while True:
    s = time.time()
    if args.video == "picam":
        f = c.read()
    else:
        ret, f = c.read()
        if not ret:
            c.open(args.video)
            time.sleep(0.5)
            continue
    f = cv2.resize(f, (400, 300))
    s = time.time()
    grey_image = bgs_mog.apply(f)
    thresh, im_bw = cv2.threshold(grey_image, 225, 255, cv2.THRESH_BINARY)
    im_dl = cv2.morphologyEx(im_bw, cv2.MORPH_OPEN, kernelOp)
    im_dl = cv2.morphologyEx(im_dl, cv2.MORPH_CLOSE, kernelCl)
    im_dl, contours, hierarchy = cv2.findContours(im_dl, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    bboxes = []
    centroids = []
    for cnt in contours:
        try:
            x, y, w, h = cv2.boundingRect(cnt)
            if args.display.lower() == 'true':
                cv2.rectangle(f, (x, y), (x + w, y + h), (255, 0, 0), 2)
            bboxes.append([x, y, x + w, y + h, 0.9])
        except:
            pass
    bboxes = np.asarray(bboxes)
    track_bbs_ids = mot_tracker.update(bboxes)
    if args.display.lower() == 'true':
        if args.numline.lower() == 'double':
            cv2.line(f, (0, y1), (400, y1), (0, 0, 255), 2)
            cv2.line(f, (0, y2), (400, y2), (255, 0, 0), 2)
        else:
            cv2.line(f, (0, y1), (400, y1), (0, 0, 255), 2)

        for ids in track_bbs_ids:
            cv2.putText(f, str(int(ids[4])), (int(ids[2]), int(ids[1])),
                        cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1)

    if args.numline.lower() == 'double':
        exit, entry = count_helper.counting_doubleline(y1, y2, track_bbs_ids)
    else:
        exit, entry = count_helper.counting_singleline(y1, track_bbs_ids)

    if entry > 0 or exit > 0:
        # Write to DB here
        camera_id = config.get('server', 'camera')
        store_id = config.get('server', 'store')
        profile_id = config.get('server', 'profile')
        recorded_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        query = "INSERT INTO pc(timestamp, people_count_entry, people_count_exit, status, store_id, profile_id, camera_id) VALUES('%s', %d, %d, %d, %s, %s, %s)" % (recorded_time, entry, exit, 0, store_id, profile_id, camera_id)  # noqa
        try:
            cur.execute(query)
            db.commit()
        except:
            print "CHECK YOUR ENTRY"

        entry_disp += entry
        exit_disp += exit

    if args.display.lower() == 'true':
        cv2.putText(f, 'Entry:' + str(entry_disp) + ', Exit:' + str(exit_disp),
                    (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
        cv2.imshow('output', f)
        k = cv2.waitKey(1)
        if k == 27:
            break

cv2.destroyAllWindows()
c.release()
enter code here

我将此文件命名为counting-sort.py并将其注册为我的/etc/systemd/system/detection.service中的服务。

问题在于我什么时候

sudo service detection start 我可以看到多个脚本实例被唤起。这是我在pi机器上htop时获得的输出。 Htop Output 任何人都可以帮助我为什么会发生这种情况?是否是由于Python的OpenCV绑定的一些内部线程?

先谢谢。

编辑:

这是我的pstree -a输出:

```

├─python counting-sort.py --display false --video picam
  │   ├─{HCEC Notify}
  │   ├─{HDispmanx Notif}
  │   ├─{HTV Notify}
  │   ├─{VCHIQ completio}
  │   ├─14*[{python}]
  │   ├─{vc.null_sink}
  │   ├─{vc.ril.camera}
  │   └─{vc.ril.video_sp}
```

0 个答案:

没有答案
相关问题