Nggarap
Nggarap

Reputation: 63

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. e.g.:

  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)

Same image name file

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

Upvotes: 0

Views: 141

Answers (1)

MarianD
MarianD

Reputation: 14191

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, e.g. 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)

Upvotes: 1

Related Questions