Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

python - Create a multi-channel image from pixel coordinates extracted from another image with OpenCV and Numpy

I have a list of mask images with the shape of(3100,3100,3),

I want to create a new image with 5 channels from each image to represent the

different colours in each mask image. I searched for the specific colours in each image

to get the pixel coordinates of each colour,

after that I want to insert these pixels into the new 5 channel image:

mask = cv2.imread('path_to_images/mask_0_1.png')
plt.imshow(mask)

mask image

# Define the colours

green= [0,255,0]
blue=[ 0, 0, 255]
yel=[255, 255, 0]
red=[ 255, 0, 0]
white=[255, 255, 255]


# create the new image with 5 channels
new_img=np.zeros( ( np.array(mask).shape[0], np.array(mask).shape[1], 5 ) )


# find each colour coordinate


new_img[0,0,1]=np.where(np.all(mask==green,axis=2))
new_img[0,0,2]=np.where(np.all(mask==blue,axis=2))
new_img[0,0,3]=np.where(np.all(mask==yel,axis=2))
new_img[0,0,4]=np.where(np.all(mask==red,axis=2))
new_img[0,0,5]=np.where(np.all(mask==white,axis=2))

it shows this error, how can I create this 5 channel image?

      > TypeError                                 Traceback (most recent call last)
     TypeError: float() argument must be a string or a number, not 'tuple'

     The above exception was the direct cause of the following exception:

     ValueError                                Traceback (most recent call last)
       <ipython-input-197-5b9c268857b2> in <module>
        19 new_img=np.zeros( ( np.array(mask).shape[0], np.array(mask).shape[1], 5 ) )
          20 
       ---> 21 new_img[0,0,1]=np.where(np.all(mask==benign,axis=2))
         22 new_img[0,0,2]=np.where(np.all(mask==blue,axis=2))
          23 new_img[0,0,3]=np.where(np.all(mask==yel,axis=2))

      ValueError: setting an array element with a sequence.
question from:https://stackoverflow.com/questions/65877220/create-a-multi-channel-image-from-pixel-coordinates-extracted-from-another-image

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Python has zero-based indices. When using five colors, the first color has index 0 and the last index 4.

  • new_img[0,0,1] will access first element of the second channel (out of five)
  • new_img[...,0] will access all elements yx of the first channel

Try the code below instead.

new_img[...,0]=np.all(mask==green,axis=2)
# ...
new_img[...,4]=np.all(mask==white,axis=2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...