اذهب إلى المحتوى
  • 0

مشكلة في كل مرة اريد تشغيل الكود يجب ادخال مسار الملفات ضمن terminal

Zeina Almakdisi

السؤال

مرحبا..

لدي خوارزمية yolo v3 الذي تقوم بتحديد ماهية الاشياء الموجودة في الصورة 

لايوجد بها مشاكل لكن في كل مرة اريد تشغيل الكود يجب ادخال مسار الملفات التالة ضمن terminal :

python yolo.py --image dog.jpg --config yolov3.cfg --weights yolov3.weights --classes yolov3.txt

هل يمكنني تثبيتهم ضمن الكود؟؟؟؟

 

import cv2
import pafy
import argparse
import numpy as np

image="dog.jpg"
classesf="yolov3.txt"
weights="yolov3.weights"
config="yolov3.cfg"
scale=0.00392
classes=None


with open(classesf,'r') as f:
    classes=[line.strip() for line in f.readlines()]
COLORS =np.random.uniform(0,255,size=(len(classes),3))
net=cv2.dnn.readNet(weights,config)


ap = argparse.ArgumentParser()
ap.add_argument('-i', '--image', required=True, 
                help = 'path to input image')
ap.add_argument('-c', '-c/--yolov3.cfg', required=True,
                help = 'path to yolo config file')
ap.add_argument('-w', '--weights', required=True,
                help = 'path to yolo pre-trained weights')
ap.add_argument('-cl', '--classes', required=True,
                help = 'path to text file containing class names')
args = ap.parse_args()


def get_output_layers(net):
    
    layer_names = net.getLayerNames()
    try:
        output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
    except:
        output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

    return output_layers


def draw_prediction(img, class_id, confidence, x, y, x_plus_w, y_plus_h):

    label = str(classes[class_id])

    color = COLORS[class_id]

    cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)

    cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)


image = cv2.imread(args.image)
def video_detector():
    while True:
        image = cv2.imread(args.image)
        Width = image.shape[1]
        Height = image.shape[0]
        blob = cv2.dnn.blobFromImage(image, 0.00392, (416,416), (0,0,0), True, crop=False)
        net.setInput(blob)
        outs = net.forward(get_output_layers(net))
        class_ids = []
        confidences = []
        boxes = []
        conf_threshold = 0.5
        nms_threshold = 0.4
        scale = 0.00392
        classes = None


        for out in outs:
            for detection in out:
                scores = detection[5:]
                class_id = np.argmax(scores)
                confidence = scores[class_id]
                if confidence > 0.5:
                    center_x = int(detection[0] * Width)
                    center_y = int(detection[1] * Height)
                    w = int(detection[2] * Width)
                    h = int(detection[3] * Height)
                    x = center_x - w / 2
                    y = center_y - h / 2
                    class_ids.append(class_id)
                    confidences.append(float(confidence))
                    boxes.append([x, y, w, h])


        indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)

        for i in indices:
            try:
                box = boxes[i]
            except:
                i = i[0]
                box = boxes[i]
            
            x = box[0]
            y = box[1]
            w = box[2]
            h = box[3]
            draw_prediction(image, class_ids[i], confidences[i], round(x), round(y), round(x+w), round(y+h))

        cv2.imshow("object detection", image)
        cv2.waitKey()
        if cv2.waitKey(1) & 0xff ==ord('q'):
            break
        cv2.imwrite("object-detection.jpg", image)
        cv2.destroyAllWindows()


conn = psycopg2.connect("dbname=Management_Center user=postgres password=123456")

[postgresql]
host=localhost
database=Management_Center
user=postgres
password=123456

if __name__ == "__main__":
    video_detector()

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

يمكنك إزالة الخاصية required و وضع قيمة افتراضية لهذه البارامترات عن طريق الخاصية default.

هذا يفترض أن يحل المشكلة الخاصة بك، بحيث في حال لم تقومي بإضافة هذه البارامترات يستعمل ما وضعتيه في ال default.

مثلاً:

ap.add_argument('-w', '--weights', default="yolov3.weights",
                help = 'path to yolo pre-trained weights')

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

يمكنك القيام بذلك عبر استخدام ملف yaml خارجي ووضع القيم فيه والتعديل عليه في أي وقت بدلا من استخدام argparse وتعتبر هذه الطريقة افضل في حال وجود عدد كبير من المتحولات الواجب إدخالها لتشغيل السكريبت, حيث يمكنك اتباع الخطوات التالية:

  1.  وضع كافة القيم  التي تقوم بتشغيل السكريبت في ملف yaml وليكن بالاسم  config.yaml
    #config.yaml
    image: "dog.jpg"
    classesf: "yolov3.txt"
    weights: "yolov3.weights"
    config: "yolov3.cfg"
    scale: 0.00392
    classes: None
  2. قراءة القيم في الملف السابق عبر رابط الملف باستخدام مكتبة yaml الموجودة في python وأسناد هذه القيم إلى متحولات من نفس الاسم منعا لحدوث اختلاط ويتم ذلك عبر الكود التالي الذي يجب وضعه في yolo.py
    import yaml
    config_path = "config.yaml" #path file
    with open(config_path, 'r') as file:
        config_para = yaml.safe_load(file)
    
    image = config_para['image']
    classesf = config_para['classesf']
    weights = config_para['weights']
    config = config_para['config']
    scale = config_para['scale']
    classes = config_para['classes']

    بعد ذلك يمكن استدعاء السكريبت بالطريقة التالية

    python yolo.py

     

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...