I made a mistake, in the output array, all the non-zeros should be 1. Sorry for my silly mistake.
thanks for all your help. I tested the three methods above, including code from Jean-François Corbett, acdr + Jean-François Corbett and mine.
It turns out the method from acdr + Jean-François Corbett is the fastest.
Here is my testing code
def test_time():
def func1(img, max_num):
w, h = img.shape
img_norm = np.zeros([w, h, max_num], np.float32)
for (i, j), val in np.ndenumerate(img):
# img_norm[i, j, val - 1] = val
img_norm[i, j, val - 1] = 0 if val == 0 else 1
return img_norm
def func2(img, max_num):
w, h = img.shape
img_norm = np.zeros([w, h, max_num], np.float32)
for idx in range(1, max_num + 1):
# img_norm[:, :, idx - 1] = idx*(img == idx)
img_norm[:, :, idx - 1] = (img == idx)
return img_norm
def func3(img, max_num):
w, h = img.shape
img_norm = np.zeros([w, h, max_num], np.float32)
for idx in range(max_num):
# img_norm[:, :, idx] = (idx+1) * (img[:, :, 0] == (idx + np.ones(shape=img[:, :, 0].shape)))
img_norm[:, :, idx] = (img == (idx + np.ones(shape=img.shape)))
return img_norm
import cv2
img_tmp = cv2.imread('dat.png', cv2.IMREAD_UNCHANGED)
img_tmp = np.asarray(img_tmp, np.int)
# img_tmp = np.array([
# [0, 0, 1, 0, 0],
# [2, 0, 3, 0, 1],
# [0, 2, 3, 1, 0],
# [0, 0, 1, 0, 0],
# [1, 0, 2, 0, 1],
# ])
img_bkp = np.array(img_tmp, copy=True)
print(img_bkp.shape)
import time
cnt = 100
maxnum = 24
start_time = time.time()
for i in range(cnt):
_ = func1(img_tmp, maxnum)
print('1 total time =', time.time() - start_time)
start_time = time.time()
for i in range(cnt):
_ = func2(img_tmp, maxnum)
print('2 total time =', time.time() - start_time)
start_time = time.time()
for i in range(cnt):
_ = func3(img_tmp, maxnum)
print('3 total time =', time.time() - start_time)
print((img_tmp == img_bkp).all())
img1 = func1(img_tmp, maxnum)
img2 = func2(img_tmp, maxnum)
img3 = func3(img_tmp, maxnum)
print(img1.shape, img2.shape, img3.shape)
print((img1 == img2).all())
print((img2 == img3).all())
print((img1 == img3).all())
# print(type(img1[0, 0, 0]), type(img2[0, 0, 0]), type(img3[0, 0, 0]))
# print('img1\n', img1[:, :, 2])
# print('img3\n', img3[:, :, 2])
The output is
(224, 224)
1 total time = 4.738261938095093
2 total time = 0.7725710868835449
3 total time = 1.5980615615844727
True
(224, 224, 24) (224, 224, 24) (224, 224, 24)
True
True
True
If there is any problem, please post it in comments.
Thanks for all your kind help!
0s in your example? You only seem to match for 1, 2 and 3.{0, 1, 2, 3}in the example, and similar for the actual data. It'd be good if the OP clarifies that.