array to image transform

274 views
Skip to first unread message

Johannes Larsch

unread,
Nov 29, 2016, 8:51:56 AM11/29/16
to Bonsai Users
Hi,

I create and return an array in a python node using the following code:


import clr
clr.AddReference("OpenCV.Net")
from OpenCV.Net import Mat

@returns(Tuple[Mat,float])
def process(input):

  steps=100

  array = Array.CreateInstance(float, 3, steps)

  for i in range(steps):
      array[0, i]= #some values
      array[1, i]= #some values
      array[2, i]=#some values


  return Mat.FromArray(array)



Now I would like to transform this array into an image with three channels. (for this example, the resulting image dimension should be 1xsteps)
How can I turn the array into an image? Either within the python node or outside in the bonsai flow.

The node 'convert to image' shows an image of dimensions 3xsteps, treating each row as a separate channel.

Gonçalo Lopes

unread,
Nov 29, 2016, 11:08:44 AM11/29/16
to Johannes Larsch, Bonsai Users
Hi Johannes,

There are basically two options:

1) Create each "plane" (or channel) as an independent matrix. So instead of having a packed array, just create one simple 1-channel array for each "color". In this case the output will be something like Tuple[Mat, Mat, Mat]. If you have this, you can send it directly to Merge (Dsp) and that will create a 3-channel matrix, which you can then convert to an image, etc.

2) If you prefer to do everything in Python, you can use Mat.FromArray directly. There is an overload that can take the number of channels, etc (the longest one). Unfortunately in this case you cannot use a rectangular 2D array. It has to be a 1D array with all the data. Fortunately, it is always possible to treat a 1D array as a 2D array with some index math:

import clr
clr.AddReference("OpenCV.Net")
from OpenCV.Net import *
from System import Array

@returns(Mat)
def generate():
  array = Array.CreateInstance(float,3 * 100)
  for i in range(100):
    array[i * 3 + 0] = i
    array[i * 3 + 1] = i / 2
    array[i * 3 + 2] = i / 3
  yield Mat.FromArray(array,10,10,Depth.F64,3)

Hope this helps!

--
You received this message because you are subscribed to the Google Groups "Bonsai Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to bonsai-users+unsubscribe@googlegroups.com.
Visit this group at https://groups.google.com/group/bonsai-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/bonsai-users/4cf583a9-ef89-4cc3-90b2-992384e6adc5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages