简体   繁体   中英

How to find common elements between two tuple

I have two images with the same size of 128x128x128. They are binary images. I want to find the common position of 1's value in two images. For example, the position (2,2) in images 1 has value 1 and (2,2) in images 2 has value 1 that considered a common position. I have tried below code but it said that I cannot do the conversation. How should I fix it? This is my error that shows in pos_common = tuple(set(pos_1) & set(pos_2))

TypeError: unhashable type: 'numpy.ndarray'
pos_1 = np.where(img1==1) #returns (array([  0,   0,   0, ..., 127]), array([  0,   0,   0, ..., 127]), array([  0,   1,   2, ..., 127]))
pos_2 = np.where(img2==1) # returns (array([  1,   4,   9, ..., 127]), array([  0,   0,   0, ..., 127]), array([  0,   1,   2, ..., 127]))
pos_common = tuple(set(pos_1) & set(pos_2)) # Error TypeError: unhashable type: 'numpy.ndarray'

-- Hey KimHee,

I would

  1. Set all values in img1 and img2 that are not equal 1 to 0
  2. Use numpy.multiply() to only retain ones where both matrices equal 1
  3. Finally, apply np.where if you still need to

Here's the code I used to reproduce your problem (assumed simple 2d arrays):

img1 = np.array([[10,10,10,1,1,1,10], [10,10,10,1,10,10,10]])
img2 = np.array([[10,10,10,10,1,10,10], [10,10,10,1,10,10,10]])

img1[img1 != 1] = 0
img2[img2 != 1] = 0

pos_common = np.multiply(img1, img2)

np.where(pos_common == 1)

Hope this helps.

I found simple solution. It may help someone

pos_common = np.where((img1==1) & (img2==1))

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