Замерить толщину проволоки полученную с веб-камеры на Centos 8
Установка библиотеки OpenCV
yum install opencv-contrib opencv-core
Установка Python библиотек необходимых для реализации:
# pip install flask
# pip install numpy
# pip install opencv-contrib-python
# pip install imutils
Все дополнения Python которые были установлены:
- Jinja2-2.11.2
- MarkupSafe-1.1.1
- Werkzeug-1.0.1
- click-7.1.2
- flask-1.1.2
- itsdangerous-1.1.0
- installed numpy-1.19.1
- opencv-contrib-python-4.2.0.34
- imutils-0.5.3
Скрипт реализации:
# USAGE
# python height_px.py --ip 0.0.0.0 --port 8009
from imutils.video import VideoStream
from flask import Response
from flask import Flask
from flask import render_template
import threading
import argparse
import datetime
import imutils
import time
import cv2
import numpy as np
class SingleMotionDetector:
def __init__(self, accumWeight=0.5):
self.accumWeight = accumWeight
self.bg = None
def update(self, image):
if self.bg is None:
self.bg = image.copy().astype("float")
return
cv2.accumulateWeighted(image, self.bg, self.accumWeight)
def detect(self, image, tVal=25):
delta = cv2.absdiff(self.bg.astype("uint8"), image)
thresh = cv2.threshold(delta, tVal, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
(minX, minY) = (np.inf, np.inf)
(maxX, maxY) = (-np.inf, -np.inf)
if len(cnts) == 0:
return None
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
(minX, minY) = (min(minX, x), min(minY, y))
(maxX, maxY) = (max(maxX, x + w), max(maxY, y + h))
return (thresh, (minX, minY, maxX, maxY))
outputFrame = None
lock = threading.Lock()
# инициализация Flask объекта
app = Flask(__name__)
# подключение к камере
vs = VideoStream(src=0).start()
time.sleep(2.0)
@app.route("/")
def index():
return Response(generate(),
mimetype = "multipart/x-mixed-replace; boundary=frame")
def detect_motion(frameCount):
global vs, outputFrame, lock
md = SingleMotionDetector(accumWeight=0.1)
total = 0
# чтение из камеры кадра
while True:
frame = vs.read()
frame = imutils.resize(frame, width=640)
with lock:
outputFrame = frame.copy()
def generate():
global outputFrame, lock
while True:
with lock:
if outputFrame is None:
continue
# преобразовать кадр в черное и белое
ret, outputFrame = cv2.threshold(outputFrame, 127, 255, 0)
# получить толщину в пикселях
i = 0
pXstarting = 0;
pXstart = 0;
pXend = 0;
while True:
b,g,r = (outputFrame[i, 320])
color = str(r) + ":" + str(g) + ":" + str(b)
if pXstarting == 0:
if color != "255:255:255":
pXstart = i
pXstarting = 1
elif pXstarting == 1:
promejutok = i - pXstart
if color == "255:255:255" and promejutok > 20:
pXend = i;
pXstarting = 2
if pXstarting == 2:
break;
i = i + 1
if i > 479:
break;
# --------------
# нарисовать стрелку сверху до объекта
i = 479
bigU0 = pXend;
bigU1 = pXend + 1;
bigU2 = pXend + 2;
bigU3 = pXend + 3;
bigU4 = pXend + 4;
bigU5 = pXend + 5;
bigU6 = pXend + 6;
bigU7 = pXend + 7;
while True:
if pXend >= i:
outputFrame[i, 320] = (0, 0, 255)
break;
else:
if bigU0 == i:
outputFrame[i, 320] = (0, 0, 255)
break;
elif bigU1 == i:
outputFrame[i, 319:321] = (0, 0, 255)
elif bigU2 == i:
outputFrame[i, 318:322] = (0, 0, 255)
elif bigU3 == i:
outputFrame[i, 317:323] = (0, 0, 255)
elif bigU4 == i:
outputFrame[i, 316:324] = (0, 0, 255)
elif bigU5 == i:
outputFrame[i, 315:325] = (0, 0, 255)
elif bigU6 == i:
outputFrame[i, 314:326] = (0, 0, 255)
elif bigU7 == i:
outputFrame[i, 313:327] = (0, 0, 255)
else:
outputFrame[i, 317:323] = (0, 0, 255)
i = i - 1
if i <= 0:
break;
# --------------
# нарисовать стрелку снизу до объекта
i = 0
bigU0 = pXstart;
bigU1 = pXstart - 1;
bigU2 = pXstart - 2;
bigU3 = pXstart - 3;
bigU4 = pXstart - 4;
bigU5 = pXstart - 5;
bigU6 = pXstart - 6;
bigU7 = pXstart - 7;
while True:
if pXstart <= i:
outputFrame[i, 320] = (0, 0, 255)
break;
else:
if bigU0 == i:
outputFrame[i, 320] = (0, 0, 255)
break;
elif bigU1 == i:
outputFrame[i, 319:321] = (0, 0, 255)
elif bigU2 == i:
outputFrame[i, 318:322] = (0, 0, 255)
elif bigU3 == i:
outputFrame[i, 317:323] = (0, 0, 255)
elif bigU4 == i:
outputFrame[i, 316:324] = (0, 0, 255)
elif bigU5 == i:
outputFrame[i, 315:325] = (0, 0, 255)
elif bigU6 == i:
outputFrame[i, 314:326] = (0, 0, 255)
elif bigU7 == i:
outputFrame[i, 313:327] = (0, 0, 255)
else:
outputFrame[i, 317:323] = (0, 0, 255)
i = i + 1
if i > 479:
break;
# --------------
# нарисовать толщину в пикселях
printHeight = "height: " + str(pXend - pXstart) + "px"
cv2.putText(outputFrame, printHeight, (30, 450), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
(flag, encodedImage) = cv2.imencode(".jpg", outputFrame)
if not flag:
continue
yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
bytearray(encodedImage) + b'\r\n')
time.sleep(0.5)
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--ip", type=str, required=True,
help="ip address of the device")
ap.add_argument("-o", "--port", type=int, required=True,
help="ephemeral port number of the server (1024 to 65535)")
ap.add_argument("-f", "--frame-count", type=int, default=32,
help="# of frames used to construct the background model")
args = vars(ap.parse_args())
t = threading.Thread(target=detect_motion, args=(
args["frame_count"],))
t.daemon = True
t.start()
app.run(host=args["ip"], port=args["port"], debug=True,
threaded=True, use_reloader=False)
vs.stop()
Для запуска скрипта:
# python height_px.py --ip 0.0.0.0 --port 8009
Для просмотра результата: http://IP-КОМПА/