python - 如何在Dlib中保存带有检测框的图像?

标签 python dlib

我正在尝试修改 Dlib 的 train_object_detector 示例,以将带有检测框的图像保存到文件中。如何使用叠加层保存图像。看完这篇answer ,我做了:

import os
import sys
import glob

import dlib
from skimage import io

if len(sys.argv) != 2:
    print(
        "Give the path to the examples/faces directory as the argument to this "
        "program. For example, if you are in the python_examples folder then "
        "execute this program by running:\n"
        "    ./train_object_detector.py ../examples/faces")
    exit()
faces_folder = sys.argv[1]


options = dlib.simple_object_detector_training_options()

options.add_left_right_image_flips = True

options.C = 5

options.num_threads = 8
options.be_verbose = True


training_xml_path = os.path.join(faces_folder, "training.xml")
testing_xml_path = os.path.join(faces_folder, "testing.xml")


# Now let's use the detector as you would in a normal application.  First we
# will load it from disk.
detector = dlib.simple_object_detector("detector.svm")

# We can look at the HOG filter we learned.  It should look like a face.  Neat!
win_det = dlib.image_window()
win_det.set_image(detector)

# Now let's run the detector over the images in the faces folder and display the
# results.
print("Showing detections on the images in the faces folder...")
win = dlib.image_window()
for f in glob.glob(os.path.join(faces_folder, "*.jpg")):
    print("Processing file: {}".format(f))
    img = io.imread(f)
    dets = detector(img)
    print("Number of faces detected: {}".format(len(dets)))
    for k, d in enumerate(dets):
        print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
            k, d.left(), d.top(), d.right(), d.bottom()))

    win.clear_overlay()
    win.set_image(img)
    win.add_overlay(dets)
    img1 = dlib.draw_rectangle(img,dets)
    outname = f + "_detected.jpg"
    #img1 = np.where(dets != 0, dets, img)
    io.imsave(outname,img1)

但是我得到这个错误:

Traceback (most recent call last):
  File "/Users/mas/dlib/python_examples/testing.py", line 74, in <module>
    img1 = dlib.draw_rectangle(img,dets)
AttributeError: 'module' object has no attribute 'draw_rectangle'

最佳答案

如果您可以使用 opencv,则可以使用 cv2.rectangle()

除了在代码中使用 img1 = dlib.draw_rectangle(img,dets),您还可以使用:

for k, d in enumerate(dets):
        print ("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(k, d.left(), d.top(), d.right(), d.bottom()))
        cv2.rectangle(img, (d.left(), d.top()), (d.right(), d.bottom()), (255, 0, 255), 2)

这将在原始图像上绘制矩形。 您可以使用 cv2.imwrite() 函数保存图像:

cv2.imwrite(outname, img)

关于python - 如何在Dlib中保存带有检测框的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32717426/

相关文章:

c++ - 具有高维标签的机器学习代码 dlib

python - 在 pandas 数据帧上逐行迭代,并有可能跳回

python - 有没有办法从单词中正确删除时态或复数?

python - Tensorflow - 使用自定义比较器对张量进行排序

opencv - 如何在 Dlib C++ 中获取头部姿势估计的 3D 坐标轴

python - 使用Python登录投资者商报并获取股票数据

python - Bash:运行后台作业并获取 pid

c++ - 使用 cv_image 实现 dlib pyramid_up

c++ - 从文本文件 dlib C++ 中读取人脸 vector