max2p
max2p

Reputation: 57

What is the right approach in this kind of broadcast?

So,what is the right approach in this broadcasting ? I have used a for loop to verify my broadcasting output. As you can see, it missed to broadcast the second element. Any idea on this?

from numpy import sum
from imageio import imread
import numpy as np
#https://github.com/glennford49/sampleImages/blob/main/cat1.png
#https://github.com/glennford49/sampleImages/blob/main/cat2.png
img1="cat1.png"
img2="cat2.png"
imageDict={}
img1=imread(img1)
img2=imread(img2)
imageDict["images1"]= (1,img1)
imageDict["images2"]=(2,img2)
listdict= list(map(lambda x:x[1], imageDict.values()))
diff= np.array(np.array(img2-listdict))
result = np.sum(diff,axis=1)/img2.size       
result = sum(result)
print("diff per pixel:",(result))
for item in diff: # verifier
    res=item / np.array(img2.size) 
    res = sum(abs(res.reshape(-1)))
    print("loop difference:",res)

prints:

diff per  pixel: 57.400979382804046 
loop difference: 57.40097938280404
loop difference: 0.0

target :

diff per  pixel: 57.400979382804046 , 0.0
loop difference: 57.40097938280404
loop difference: 0.0

Upvotes: 1

Views: 48

Answers (1)

Akshay Sehgal
Akshay Sehgal

Reputation: 19322

First, np.stack the images instead of the dict and list. This gives you a (2, 276, 183, 3) tensor. which is broadcastable with (276, 183, 3).

Second, In the last sum you need to avoid using sum and instead use np.sum(axis=(1,2)). This will leave the axis=0 from being summed and give you the 2 difference values you are looking for.

import numpy as np

#Replace with your cat images
img1=np.random.random((276, 183, 3))
img2=np.random.random((276, 183, 3))

imageDict["images1"]= (1,img1)
imageDict["images2"]=(2,img2)
listdict = list(map(lambda x:x[1], imageDict.values()))

diff = img2 - listdict
result = np.sum(diff, axis=1)/img2.size
result = np.sum(result, axis=(1,2))
result
array([0.00016465, 0.        ])

Upvotes: 2

Related Questions