Exemple #1
0
def inference():
    net = dnn.readNetFromCaffe(args.caffe_prototxt_path, args.caffe_model_path)
    input_size = [int(v.strip()) for v in args.input_size.split(",")]
    witdh = input_size[0]
    height = input_size[1]
    priors = define_img_size(input_size)
    result_path = args.results_path
    imgs_path = args.imgs_path
    if not os.path.exists(result_path):
        os.makedirs(result_path)
    listdir = os.listdir(imgs_path)
    for file_path in listdir:
        img_path = os.path.join(imgs_path, file_path)
        img_ori = cv2.imread(img_path)
        rect = cv2.resize(img_ori, (witdh, height))
        rect = cv2.cvtColor(rect, cv2.COLOR_BGR2RGB)
        net.setInput(dnn.blobFromImage(rect, 1 / image_std, (witdh, height), 127))
        time_time = time.time()
        boxes, scores = net.forward(["boxes", "scores"])
        print("inference time: {} s".format(round(time.time() - time_time, 4)))
        boxes = np.expand_dims(np.reshape(boxes, (-1, 4)), axis=0)
        scores = np.expand_dims(np.reshape(scores, (-1, 2)), axis=0)
        boxes = convert_locations_to_boxes(boxes, priors, center_variance, size_variance)
        boxes = center_form_to_corner_form(boxes)
        boxes, labels, probs = predict(img_ori.shape[1], img_ori.shape[0], scores, boxes, args.threshold)
        for i in range(boxes.shape[0]):
            box = boxes[i, :]
            cv2.rectangle(img_ori, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
        cv2.imwrite(os.path.join(result_path, file_path), img_ori)
        print("result_pic is written to {}".format(os.path.join(result_path, file_path)))
        cv2.imshow("ultra_face_ace_opencvdnn_py", img_ori)
        cv2.waitKey(-1)
    cv2.destroyAllWindows()
Exemple #2
0
 def load_model(self, modelTxt, modelBin, classDict, width=300, height = 300, scale = 0.00783, meanVal = 127.5):
     self.net = dnn.readNetFromCaffe(modelTxt, modelBin)
     self.dict = classDict
     self.width = width
     self.height = height
     self.scale = scale
     self.mean_val = meanVal
    def __init__(self,
                 prototype: Path = None,
                 model: Path = None,
                 embedder: Path = None,
                 labelencoder: Path = None,
                 recognizer: Path = None,
                 confidenceThreshold: float = 0.8):
        self.prototype = prototype
        self.model = model
        self.confidenceThreshold = confidenceThreshold
        if self.prototype is None:
            raise FaceRecognizerException(
                "must specify prototype '.prototxt.txt' file "
                "path")
        if self.model is None:
            raise FaceRecognizerException(
                "must specify model '.caffemodel' file path")
        self.classifier = readNetFromCaffe(str(prototype), str(model))

        if embedder is None:
            raise FaceRecognizerException(
                "must specify Face Embedding '.t7' file "
                "path")

        if recognizer is None:
            raise FaceRecognizerException("must specify face recognizor")

        if labelencoder is None:
            raise FaceRecognizerException("must specify Classifier")

        self.embedder = readNetFromTorch(str(embedder))
        # load the actual face recognition model along with the label encoder
        self.recognizer = pickle.loads(open(str(recognizer), "rb").read())
        self.le = pickle.loads(open(str(labelencoder), "rb").read())
Exemple #4
0
def recognition_word(img, boxes, rec_modelPath):
    deploy = os.path.join(rec_modelPath, 'deploy.prototxt')
    weights = os.path.join(rec_modelPath, 'weights.caffemodel')
    labelPath = os.path.join(rec_modelPath, 'label.txt')

    text_ = []
    Confidence_ = []


    row = open(labelPath, encoding='gbk').read().strip().split("\n")
    class_label = row

    net = dnn.readNetFromCaffe(deploy, weights)

    for box in boxes:
        img_word = img[int(box[1]):int(box[5]), int(box[0]):int(box[4])].copy()
        img_word = cv.cvtColor(img_word, cv.COLOR_RGB2GRAY)
        #img_word = img_word[:, :, 0]
        img_word = cv.resize(img_word, (64, 64))

        blob = dnn.blobFromImage(img_word, 1, (64, 64), (0.))
        text, Confidence = model_predict(blob, net, class_label, 1)

        text_.append(text[0])
        Confidence_.append(round(Confidence[0], 2))

    # print(text_)
    # print(Confidence_)
    return text_, Confidence_
Exemple #5
0
    def __init__(self):
        # Parametros necesarios para graficar.
        self.cap = None
        self.h = 0  # alto de la imagen capturada
        self.w = 0  # ancho de la imagen captirada
        self.old_frame = None
        # Detecciones
        self.confthr = .5  # umbral de confiabilidad
        self.dimthr = .25  # umbral de dimensión (.5 ~50% del ancho total de la imágen)
        self.box_startXY = []
        self.box_endXY = []
        self.detections = []  # detecciones
        # radar: modelo y directorio de salida
        self.prototxt = './models/MobileNetSSD_deploy.prototxt.txt'
        self.modelo = './models/MobileNetSSD_deploy.caffemodel'
        self.dir_out = './out/'

        self.CLASSES = [
            "background", "aeroplane", "bicycle", "bird", "boat", "bottle",
            "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse",
            "motorbike", "person", "pottedplant", "sheep", "sofa", "train",
            "tvmonitor"
        ]
        self.IGNORE = {
            "background", "aeroplane", "bicycle", "bird", "boat", "bottle",
            "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike",
            "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"
        }

        # iniciamos el modelo
        self.net = readNetFromCaffe(self.prototxt, self.modelo)

        self.flag = False
Exemple #6
0
    def __init__(self) :
        self.inWidth = 300
        self.inHeight = 300
        self.confThreshold = 0.5

        self.prototxt = osp.join(BASE_DIR, 'weights/deploy.prototxt')
        self.caffemodel = osp.join(BASE_DIR, 'weights/res10_300x300_ssd_iter_140000.caffemodel')
        self.net = dnn.readNetFromCaffe(self.prototxt, self.caffemodel)
    def __init__(self):
        """ResnetFaceDetecor class rewrite version
        """

        prototxt = 'face_detector/deploy.prototxt'
        caffemodel = 'face_detector/res10_300x300_ssd_iter_140000.caffemodel'
        self.inWidth = 300
        self.inHeight = 300
        self.net = dnn.readNetFromCaffe(prototxt, caffemodel)
def caffe2wxf(path):
    model = opencv.readNetFromCaffe(path + ".prototxt", path + ".caffemodel")
    layers = model.getLayerNames()
    npy = {}
    for i in layers:
        try:
            npy[i] = model.getParam(i)
        except Exception:
            pass
    wxf.export(npy, path + '.wxf', target_format='wxf')
Exemple #9
0
 def __init__(self,
              name: str = 'dnn.readNetFromCaffe',
              find_best: bool = True,
              color: tuple = (0, 255, 0)):
     super().__init__(name=name, find_best=find_best, color=color)
     model_filename, config_filename = ModelsSource.get_model_cv2_dnn_cafee_filename(
     )
     self._net = dnn.readNetFromCaffe(config_filename, model_filename)
     self.add_not_none_option('config', config_filename)
     self.add_not_none_option('model', model_filename)
Exemple #10
0
def detect(frame):
    blob = dnn.blobFromImage(frame, 1, (1024, 768), (0, 0, 0),True)
    net = dnn.readNetFromCaffe(cm_path + 'density.prototxt', cm_path + 'density.caffemodel')

    net.setInput(blob)
    density = net.forward()

    density = density/1000.0

    person_num = np.sum(density[:])
    return int(person_num)
Exemple #11
0
 def __init__(self, prototype: Path=None, model: Path=None,
              confidenceThreshold: float=0.6):
     self.prototype = prototype
     self.model = model
     self.confidenceThreshold = confidenceThreshold
     if self.prototype is None:
         raise FaceDetectorException("must specify prototype '.prototxt.txt' file "
                                     "path")
     if self.model is None:
         raise FaceDetectorException("must specify model '.caffemodel' file path")
     self.classifier = readNetFromCaffe(str(prototype), str(model))
Exemple #12
0
 def __init__(
         self,
         dnnModelFile="./resources/face_detectors/facedetect_dnn_res10_300x300_ssd_iter_140000_fp16.caffemodel",
         dnnConfigFile="./resources/face_detectors/facedetect_dnn_deploy.prototxt",
         confidenceThreshold=.6,
         postProcessCallback=None):
     super().__init__(postProcessCallback=postProcessCallback)
     # check files
     open(dnnConfigFile, 'r').close()
     open(dnnModelFile, 'r').close()
     self.net = dnn.readNetFromCaffe(dnnConfigFile, dnnModelFile)
     self.confidenceThreshold = confidenceThreshold
def face_detection():
    net = dnn.readNetFromCaffe(prototxt, caffemodel)
    #cap = cv.VideoCapture(0)
    #cap = cv.VideoCapture("E:/视频库/srcImage/OneStopMoveEnter1cor.avi")
    frame = cv.imread("face01.jpg")

    while True:
        #ret, frame = cap.read()

        cols = frame.shape[1]
        rows = frame.shape[0]

        net.setInput(
            dnn.blobFromImage(frame, 1.0, (inWidth, inHeight),
                              (104.0, 177.0, 123.0), False, False))
        detections = net.forward()

        perf_stats = net.getPerfProfile()
        print('Inference time:  %.2f ms' %
              (perf_stats[0] / cv.getTickFrequency() * 1000))

        for i in range(detections.shape[2]):
            confidence = detections[0, 0, i, 2]
            if confidence > confThreshold:
                global count
                count += 1
                print(confidence)

                xLeftBottom = int(detections[0, 0, i, 3] * cols)
                yLeftBottom = int(detections[0, 0, i, 4] * rows)
                xRightTop = int(detections[0, 0, i, 5] * cols)
                yRightTop = int(detections[0, 0, i, 6] * rows)

                cv.rectangle(frame, (xLeftBottom, yLeftBottom),
                             (xRightTop, yRightTop), (0, 255, 0))
                label = "face: %.4f" % confidence
                labelSize, baseLine = cv.getTextSize(label,
                                                     cv.FONT_HERSHEY_SIMPLEX,
                                                     0.5, 1)

                cv.rectangle(
                    frame, (xLeftBottom, yLeftBottom - labelSize[1]),
                    (xLeftBottom + labelSize[0], yLeftBottom + baseLine),
                    (255, 255, 255), cv.FILLED)
                cv.putText(frame, label, (xLeftBottom, yLeftBottom),
                           cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))

        cv.imshow("detections", frame)
        print('the num of face: %d ' % count)
        if cv.waitKey(0) != -1:
            break
    def __init__(
        self,
        prototxt_path: str,
        model_path: str,
        min_confidence: float,
    ):
        """Initialize configuration and load pretrained net.

        Args:
            prototxt_path: Path to net .prototxt file
            model_path: Path to net .caffemodel file
            min_confidence: Minimum confidence for accepting pe
        """
        self._min_confidence = min_confidence
        self._net = dnn.readNetFromCaffe(prototxt_path, model_path)
Exemple #15
0
  def load_model(self):
    global sess, age, gender, train_mode, images_pl
    global fa
    global face_net
    global emotion_labels, emotion_classifier, emotion_target_size
    global parentDir
    
    # parser = argparse.ArgumentParser()
    # parser.add_argument("--model_path", "--M", default="./models", type=str, help="Model Path")
    # args = parser.parse_args()    
    sess, age, gender, train_mode, images_pl = self.load_network(parentDir + "./models")   

    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor(parentDir + "\\src\\dist\\FaceSDK\\face_recognition_models\\models\\shape_predictor_68_face_landmarks.dat")
    fa = FaceAligner(predictor, desiredFaceWidth=160)   
    
    face_model_txt = parentDir + '/trained_models/face_models/deploy_resnet.prototxt'
    face_model_bin = parentDir + '/trained_models/face_models/res10_300x300_ssd_iter_140000_fp16.caffemodel'
    face_net = dnn.readNetFromCaffe(face_model_txt, face_model_bin) 
    def face_detection(self):
        net = dnn.readNetFromCaffe(prototxt, caffemodel)
        net.setInput(
            dnn.blobFromImage(self.image, 1.0, (inWidth, inHeight),
                              (104.0, 177.0, 123.0), False))
        detections = net.forward()
        # print(detections.shape)
        # print(detections)
        cols = self.image.shape[1]
        rows = self.image.shape[0]
        for i in range(detections.shape[2]):
            confidence = detections[0, 0, i, 2]
            if confidence > confThreshold:
                self.count += 1
                # print(confidence)

                xLeftBottom = int(detections[0, 0, i, 3] * cols)
                yLeftBottom = int(detections[0, 0, i, 4] * rows)
                xRightTop = int(detections[0, 0, i, 5] * cols)
                yRightTop = int(detections[0, 0, i, 6] * rows)

                cv2.rectangle(self.image, (xLeftBottom, yLeftBottom),
                              (xRightTop, yRightTop), (0, 255, 0))
                label = "face: %.4f" % confidence
                # labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
                cv2.putText(self.image, label, (xLeftBottom, yLeftBottom),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))

        cvRGBImg = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
        qi = QImage(cvRGBImg.data, cvRGBImg.shape[1], cvRGBImg.shape[0],
                    cvRGBImg.shape[1] * 3, QImage.Format_RGB888)
        pix = QPixmap.fromImage(qi)

        self.label2.setPixmap(pix)
        self.label2.show()

        self.label3.clear()
        if self.count > 0:
            self.label3.setText("图中检测到{}张人脸".format(self.count))
        else:
            self.label3.setText("图中未检测到人脸")
Exemple #17
0
    def __init__(self,Tello:myTello):
        self.prev_flight_data = None
        self.record = False
        self.tracking = False
        self.keydown = False
        self.date_fmt = '%Y-%m-%d_%H%M%S'
        self.speed = 20
        self.speed2 = 10
        self.drone = Tello
        # self.init_drone()

        self.caffe_prototxt_path = "../Face_Distance/model/RFB-320.prototxt"
        self.caffe_model_path = "../Face_Distance/model/RFB-320.caffemodel"
        self.net = dnn.readNetFromCaffe(self.caffe_prototxt_path, self.caffe_model_path)

        # container for processing the packets into frames
        # self.container = av.open(self.drone.get_video_stream())
        # self.vid_stream = self.drone.container.streams.video[0]
        self.out_file = None
        self.out_stream = None
        self.out_name = None
        self.start_time = time.time()

        # tracking a color
        green_lower = (30, 50, 50)
        green_upper = (80, 255, 255)
        #red_lower = (0, 50, 50)
        # red_upper = (20, 255, 255)
        # blue_lower = (110, 50, 50)
        # upper_blue = (130, 255, 255)
        self.track_cmd = ""
        self.ball_tracker = ball_tracker(self.drone.height,
                               self.drone.width,
                               green_lower, green_upper)

        self.face_tracker = face_tracker(self.drone.height,
                               self.drone.width,)
#coding=utf-8
from cv2 import dnn
import cv2
import e2e

inWidth = 720
inHeight = 1024
WHRatio = inWidth / float(inHeight)
inScaleFactor = 0.007843
meanVal = 127.5

classNames = ('background',
              'plate')
net = dnn.readNetFromCaffe("MobileNetSSD_test.prototxt","lpr.caffemodel")

import time

def detect(cpp):
    frame = cv2.imread(cpp)
    blob = dnn.blobFromImage(frame, inScaleFactor, (inWidth, inHeight), meanVal)
    net.setInput(blob)
    t0 = time.time()
    detections = net.forward()
    print time.time() - t0

    cols = frame.shape[1]
    rows = frame.shape[0]

    if cols / float(rows) > WHRatio:
        cropSize = (int(rows * WHRatio), rows)
    else:
#coding=utf-8
from cv2 import dnn
import cv2

inWidth = 720
inHeight = 1024

#inWidth = 1024
#inHeight = 720  #for mssd512_voc.caffemodel

WHRatio = inWidth / float(inHeight)
inScaleFactor = 0.007843
meanVal = 127.5

classNames = ('background', 'plate')
net = dnn.readNetFromCaffe("lpr.prototxt", "lpr.caffemodel")

import time


def detect(cpp):
    frame = cv2.imread(cpp)
    blob = dnn.blobFromImage(frame, inScaleFactor, (inWidth, inHeight),
                             meanVal)
    net.setInput(blob)
    t0 = time.time()
    detections = net.forward()
    print time.time() - t0

    cols = frame.shape[1]
    rows = frame.shape[0]
Exemple #20
0
#coding=utf-8
from cv2 import dnn
import cv2
import e2e

inWidth = 720
inHeight = 1024
WHRatio = inWidth / float(inHeight)
inScaleFactor = 0.007843
meanVal = 127.5

classNames = ('background', 'plate')
net = dnn.readNetFromCaffe("MobileNetSSD_test.prototxt", "lpr.caffemodel")

import time


def detect(cpp):
    frame = cv2.imread(cpp)
    blob = dnn.blobFromImage(frame, inScaleFactor, (inWidth, inHeight),
                             meanVal)
    net.setInput(blob)
    t0 = time.time()
    detections = net.forward()
    print time.time() - t0

    cols = frame.shape[1]
    rows = frame.shape[0]

    if cols / float(rows) > WHRatio:
        cropSize = (int(rows * WHRatio), rows)
Exemple #21
0
from __future__ import print_function
import numpy as np
import cv2
from cv2 import dnn
import timeit

def timeit_forward(net):
    print("Runtime:", timeit.timeit(lambda: net.forward(), number=10))

def get_class_list():
    with open('synset_words.txt', 'rt') as f:
        return [x[x.find(" ") + 1:] for x in f]

blob = dnn.blobFromImage(cv2.imread('space_shuttle.jpg'), 1, (224, 224), (104, 117, 123), False)
print("Input:", blob.shape, blob.dtype)

net = dnn.readNetFromCaffe('bvlc_googlenet.prototxt', 'bvlc_googlenet.caffemodel')
net.setInput(blob)
prob = net.forward()
#timeit_forward(net)        #Uncomment to check performance

print("Output:", prob.shape, prob.dtype)
classes = get_class_list()
print("Best match", classes[prob.argmax()])
You can find the original code here:
https://github.com/opencv/opencv/blob/24bed38c2b2c71d35f2e92aa66648f8485a70892/samples/dnn/resnet_ssd_face_python.py
"""
import cv2 as cv
from cv2 import dnn

WIDTH = 300
HEIGHT = 300

PROTOTXT = './deploy.prototxt'
MODEL = './res10_300x300_ssd_iter_140000.caffemodel'

CASCADES_FILE = "./lbpcascade_frontalface_improved.xml"
CASCADES = cv.CascadeClassifier(CASCADES_FILE)

NET = dnn.readNetFromCaffe(PROTOTXT, MODEL)
VIDEO = 'test.avi'


def get_lbp_facebox(image):
    """
    Get the bounding box fo faces in image by LBP feature.
    """
    rects = CASCADES.detectMultiScale(image, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
                                      flags=cv.CASCADE_SCALE_IMAGE)
    if len(rects) == 0:
        return []
    for rect in rects:
        rect[2] += rect[0]
        rect[3] += rect[1]
    return rects
Exemple #23
0
def dnn_show_result(prob, classes, n):
    y = sorted(prob[0], reverse=True)  # 从大到小排序
    #异常踩坑:# 前n名 # range(50)
    # range(50)报错,因为range返回range对象,不返回数组对象
    # 将range对象转换为list列表对象在进行遍历
    z = list(range(n))
    for i in range(0, n):
        z[i] = np.where(prob[0] == y[i])[0][0]
        print(u"第", i + 1, u"匹配:", classes[z[i]], end='')
        print(u"类所在行:", z[i] + 1, "  ", u"可能性:", y[i])


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("USAGE: googlenet.py images/tiger.jpg")
        sys.exit()
    print("dddd")
    fn = sys.argv[1]
    blob = dnn.blobFromImage(cv2.imread(fn), 1, (224, 224), (104, 117, 123))
    print("Input:", blob.shape, blob.dtype)

    net = dnn.readNetFromCaffe(cm_path + 'bvlc_googlenet.prototxt',
                               cm_path + 'bvlc_googlenet.caffemodel')
    net.setInput(blob)
    prob = net.forward()
    print("Output:", prob.shape, prob.dtype)

    classes = get_class_list()
    dnn_show_result(prob, classes, 3)
Exemple #24
0
 def __init__(self, model_path, weights_path):
     self.net = readNetFromCaffe(model_path, weights_path)
Exemple #25
0
from __future__ import print_function
import numpy as np
import cv2
from cv2 import dnn
import timeit


def timeit_forward(net):
    print("Runtime:", timeit.timeit(lambda: net.forward(), number=10))


def get_class_list():
    with open('synset_words.txt', 'rt') as f:
        return [x[x.find(" ") + 1:] for x in f]


blob = dnn.blobFromImage(cv2.imread('space_shuttle.jpg'), 1, (224, 224),
                         (104, 117, 123), False)
print("Input:", blob.shape, blob.dtype)

net = dnn.readNetFromCaffe('bvlc_googlenet.prototxt',
                           'bvlc_googlenet.caffemodel')
net.setInput(blob)
prob = net.forward()
#timeit_forward(net)        #Uncomment to check performance

print("Output:", prob.shape, prob.dtype)
classes = get_class_list()
print("Best match", classes[prob.argmax()])
Exemple #26
0
    "background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus",
    "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike",
    "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"
]
colors = np.random.uniform(0, 255, size=(len(labels), 3))

image = cv2.imread('bali-crop.jpg')

#prepare test image
(h, w) = image.shape[:2]

#prepare model network
blob = dnn.blobFromImage(image, 1, (512, 512))
prototxt = "models\VGGNet\VOC0712Plus\SSD_512x512_ft\deploy.prototxt"
model = "models\VGGNet\VOC0712Plus\SSD_512x512_ft\VGG_VOC0712Plus_SSD_512x512_ft_iter_160000.caffemodel"
net = dnn.readNetFromCaffe(prototxt, model)

#feed in image and get result
net.setInput(blob)
t = time.time()
prob = net.forward()
print("Runtime:", time.time() - t)

#diaplay result
for i in np.arange(0, prob.shape[2]):
    confidence = prob[0, 0, i, 2]
    if confidence > 0.4:  #change threshold value to get the result you want
        # get data from prob
        index = int(prob[0, 0, i, 1])
        box = prob[0, 0, i, 3:7] * np.array([w, h, w, h])
        (x, y, endX, endY) = box.astype("int")
parser = argparse.ArgumentParser()
parser.add_argument("--video", help="number of video device", default=0)
parser.add_argument("--prototxt", default="mobilenet_v2_deploy.prototxt")
parser.add_argument("--caffemodel", default="mobilenet_v2.caffemodel")
parser.add_argument("--classNames", default="synset.txt")
args = parser.parse_args()

width = 480
height = 640
camera = picamera.PiCamera()
camera.resolution = (width, height)
camera.rotation = 90
offset = 22

net = dnn.readNetFromCaffe(args.prototxt, args.caffemodel)
f = open(args.classNames, 'r')
rawClassNames = f.readlines()
classNames = []
for nameStr in rawClassNames:
    spaceIndex = nameStr.find(' ')
    nameStr = nameStr[spaceIndex:-2]
    classNames.append(nameStr)

inWidth = 224
inHeight = 224
inScaleFactor = 0.017
meanVal = (103.94, 116.78, 123.68)
resultText = None

pygame.init()
 def __init__(self, prototype, model, confidence_threshold: float = 0.6):
     self.prototype = prototype
     self.model = model
     self.confidence_threshold = confidence_threshold
     self.classifier = readNetFromCaffe(str(prototype), str(model))
Exemple #29
0
    "贵": "GUIB",
    "云": "YUN",
    "川": "CHUAN"
}

plateTypeName = ["蓝", "黄", "绿", "白", "黑 "]
fontC = ImageFont.truetype("Font/platech.ttf", 38,
                           0)  # 加载中文字体,38表示字体大小,0表示unicode编码
inWidth = 480  # 480  # from ssd.prototxt ,540,960,720,640,768,设置图片宽度
inHeight = 640  # 640 ,720,1280,960,480,1024
WHRatio = inWidth / float(inHeight)  # 计算宽高比
inScaleFactor = 0.007843  # 1/127.5
meanVal = 127.5

classNames = ('background', 'plate')
net = dnn.readNetFromCaffe("model/MobileNetSSD_test.prototxt",
                           "model/lpr.caffemodel")  # 读入模型文件
net.setPreferableBackend(dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(dnn.DNN_TARGET_CPU)  # 使用cpu

# net.setPreferableTarget(dnn.DNN_TARGET_OPENCL)   # 启用GPU OPENCL 加速 ,默认FP32
# net.setPreferableTarget(dnn.DNN_TARGET_OPENCL_FP16)   # only for intel xianka test faster speed


# 画车牌定位框及识别出来的车牌字符,返回标记过的图片
def drawPred(frame, label, left, top, right, bottom):
    # 画车牌定位边框.左上点,右下点,红色,边框粗细:2
    cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
    # 画车牌字符
    img = Image.fromarray(frame)
    draw = ImageDraw.Draw(img)
    draw.text((left + 1, top - 38), label, (0, 0, 255),
    import cv2 as cv
except ImportError:
    raise ImportError('Can\'t find OpenCV Python module. If you\'ve built it from sources without installation, '
                      'configure environemnt variable PYTHONPATH to "opencv_build_dir/lib" directory (with "python3" subdirectory if required)')

from cv2 import dnn

inWidth = 300
inHeight = 300
confThreshold = 0.5

prototxt = 'face_detector/deploy.prototxt'
caffemodel = 'face_detector/res10_300x300_ssd_iter_140000.caffemodel'

if __name__ == '__main__':
    net = dnn.readNetFromCaffe(prototxt, caffemodel)
    cap = cv.VideoCapture(0)
    while True:
        ret, frame = cap.read()
        cols = frame.shape[1]
        rows = frame.shape[0]

        net.setInput(dnn.blobFromImage(frame, 1.0, (inWidth, inHeight), (104.0, 177.0, 123.0), False, False))
        detections = net.forward()

        perf_stats = net.getPerfProfile()

        print('Inference time, ms: %.2f' % (perf_stats[0] / cv.getTickFrequency() * 1000))

        for i in range(detections.shape[2]):
            confidence = detections[0, 0, i, 2]
 def _get_classifier(self):
     prototxt_p = self.model_p / "deploy.prototxt.txt"
     caffemodel_p = self.model_p / "res10_300x300_ssd_iter_140000.caffemodel"
     return readNetFromCaffe(str(prototxt_p), str(caffemodel_p))
Exemple #32
0
import cv2 as cv
from cv2 import dnn


img = cv.imread('/home/king/Desktop/1.png')
net = dnn.readNetFromCaffe('./res/deploy.prototxt', './res/res10_300x300_ssd_iter_140000.caffemodel')

net.setInput(dnn.blobFromImage(img, 1.0, (300, 300), (104.0, 177.0, 123.0), False, False))
detections = net.forward()

cols = img.shape[1]
rows = img.shape[0]

for i in range(detections.shape[2]):
    confidence = detections[0, 0, i, 2]
    if confidence > 0.5:
        xLeftBottom = int(detections[0, 0, i, 3] * cols)
        yLeftBottom = int(detections[0, 0, i, 4] * rows)
        xRightTop = int(detections[0, 0, i, 5] * cols)
        yRightTop = int(detections[0, 0, i, 6] * rows)

        cv.rectangle(img, (xLeftBottom, yLeftBottom), (xRightTop, yRightTop), (0, 0, 255))
cv.imshow('img', img)
cv.waitKey(0)
cv.destroyAllWindows()
Exemple #33
0
plateTypeName = ["蓝", "黄", "绿", "白", "黑 "]
import os

dir_path = os.getcwd()

fontC = ImageFont.truetype(dir_path + "/hyperlpr_py3/Font/platech.ttf", 30,
                           0)  # 加载中文字体,38表示字体大小,0表示unicode编码
inWidth = 480  # 480  # from ssd.prototxt ,540,960,720,640,768,设置图片宽度
inHeight = 640  # 640 ,720,1280,960,480,1024
WHRatio = inWidth / float(inHeight)  # 计算宽高比
inScaleFactor = 0.007843  # 1/127.5
meanVal = 127.5

classNames = ('background', 'plate')
net = dnn.readNetFromCaffe(
    dir_path + "/hyperlpr_py3/model/MobileNetSSD_test.prototxt",
    dir_path + "/hyperlpr_py3/model/lpr.caffemodel")  # 读入模型文件
net.setPreferableBackend(dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(dnn.DNN_TARGET_CPU)  # 使用cpu

# net.setPreferableTarget(dnn.DNN_TARGET_OPENCL)   # 启用GPU OPENCL 加速 ,默认FP32
# net.setPreferableTarget(dnn.DNN_TARGET_OPENCL_FP16)   # only for intel xianka test faster speed


# 画车牌定位框及识别出来的车牌字符,返回标记过的图片
def drawPred(frame, label, left, top, right, bottom):
    # 画车牌定位边框.左上点,右下点,红色,边框粗细:2
    cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
    # 画车牌字符
    img = Image.fromarray(frame)
    draw = ImageDraw.Draw(img)