Skip to content
This repository has been archived by the owner on Nov 21, 2023. It is now read-only.

use opencv instead of numpy to subtract pixel means #50

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

vesor
Copy link

@vesor vesor commented Jan 27, 2018

Using numpy to subtract pixel means is slow when image is not small.
As we already using opencv to do image resizing, I think it' better to also use opencv to do subtraction.
By using opencv, it can reduce total inference time by about 10ms on my 8700K machine for an image with size 1352x900.

The following test code shows the correctness and performance gain.
Some test results:
On 8700K machine:
('numpy timecost', 0.025714427947998046)
('opencv timecost', 0.0030607531070709227)
On 6850K machine:
('numpy timecost', 0.032919152021408084)
('opencv timecost', 0.004819504976272583)
On some Azure cheap instance:
numpy timecost 0.2105223798751831
opencv timecost 0.03022796869277954

import cv2
import numpy as np
import time

# prepare fake data
pixel_means = np.array([[[102.9801, 115.9465, 122.7717]]])
pixel_means_negative = -pixel_means
input_im = np.random.randint(256, size=(900, 1352, 3), dtype='uint8')

# test code, refer to the prep_im_for_blob() function
test_iteration = 1000
im = input_im.astype(np.float32)
t = time.time()
for _ in range(test_iteration):
    im -= pixel_means
    im -= pixel_means_negative
timecost = time.time() - t
assert np.allclose(im, input_im, rtol=0, atol=1e-4)
print("numpy timecost", timecost/test_iteration)

im = input_im.astype(np.float32)
t = time.time()
for _ in range(test_iteration):
    im = cv2.subtract(im, pixel_means.reshape((1,) + im.shape[-1:]))
    im = cv2.subtract(im, pixel_means_negative.reshape((1,) + im.shape[-1:]))
timecost = time.time() - t
assert np.allclose(im, input_im, rtol=0, atol=1e-4)
print("opencv timecost", timecost/test_iteration)

Copy link
Contributor

@gadcam gadcam left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can remove the commented line.
I could reproduce the performance speedud on my machine :
numpy timecost 0.03528222131729126
opencv timecost 0.01583207130432129

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants