简体   繁体   中英

Millisecond for image name file not increasing when writing some images in sequence (cv2.imwrite) Python

I have face detection script, and it's working as intended but I want to extract detected and cropped face as well. Then I want to differentiate the image name file with millisecond. eg:

  1. 17.564.jpg
  2. 17.777.jpg
  3. 17.987.jpg

My problem is, the millisecond not increasing/updating (All the rest of the images have same timestamp, the i variable is increasing). I already put strftime inside the for loop.

This is my code, and the output:

i = 0
now = time.time()
mlsec = repr(now).split('.')[1][:3]

for (x, y, w, h) in faces:
    cv2.rectangle(readImg, (x, y), (x + w, y + h), (0, 255, 0), 1)
    crop = readImg[y:y + h, x:x + w]
    i += 1
    ms = "%d. " % i + time.strftime("%S.{}".format(mlsec))
    cv2.imwrite("crop\\%s.jpg" % ms, crop)

相同的图像名称文件

Btw, sorry for my english. I'll edit my question if someone still not understand what I'm asking. Thank you in advance.

Your command

mlsec = repr(now).split('.')[1][:3]

is out of your loop . Put it inside:

i = 0

for (x, y, w, h) in faces:
    cv2.rectangle(readImg, (x, y), (x + w, y + h), (0, 255, 0), 1)
    crop = readImg[y:y + h, x:x + w]
    i += 1
    mlsec = repr(now).split('.')[1][:3]                         # <------ Here
    ms = "%d. " % i + time.strftime("%S.{}".format(mlsec))
    cv2.imwrite("crop\\%s.jpg" % ms, crop)

Maybe you don't need the exact milliseconds, you only want different times. So put a wait in your loop, eg 100 milliseconds:

import time

i = 0

for (x, y, w, h) in faces:
    time.sleep(0.1)           # <------------------------------- wait 0.1s = 100 ms
    cv2.rectangle(readImg, (x, y), (x + w, y + h), (0, 255, 0), 1)
    crop = readImg[y:y + h, x:x + w]
    i += 1
    mlsec = repr(now).split('.')[1][:3]                         # <------ Here
    ms = "%d. " % i + time.strftime("%S.{}".format(mlsec))
    cv2.imwrite("crop\\%s.jpg" % ms, crop)

Note:

Instead of manually control your i variable, you may use the enumerate() built-in function (which is more Pythonic):

import time

for i, (x, y, w, h) in enumerate(faces):       <--- Here; your i += 1 command I deleted 
    time.sleep(0.1)
    cv2.rectangle(readImg, (x, y), (x + w, y + h), (0, 255, 0), 1)
    crop = readImg[y:y + h, x:x + w]
    mlsec = repr(now).split('.')[1][:3]
    ms = "%d. " % i + time.strftime("%S.{}".format(mlsec))
    cv2.imwrite("crop\\%s.jpg" % ms, crop)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM