Numpy: slicing a volume using a matrix












3















I have a 3D numpy volume and a 2D numpy matrix:



foo = np.random.rand(20,20,10)
amin = np.argmin(foo, axis=2)


i would like to use amin variable to slice the volume in the same way np.min would do:



grid = np.indices(min.shape)
idcs = np.stack([grid[0], grid[1], min])

fmin = foo[idcs[0], idcs[1], idcs[2]]


problem is that i can't use np.min because i also need the amin neighbors for interpolation reasons, something that i would obtain doing:



pre  = foo[idcs[0], idcs[1], np.clip(idcs[2]-1, 0, 9)]
post = foo[idcs[0], idcs[1], np.clip(idcs[2]+1, 0, 9)]


Is there a more pythonic (nupyic) way to do this without creating an np.grid? something like:



foo[:,:,amin-1:amin+1]


that actually works (i would care about margin handling with an early-padding)










share|improve this question





























    3















    I have a 3D numpy volume and a 2D numpy matrix:



    foo = np.random.rand(20,20,10)
    amin = np.argmin(foo, axis=2)


    i would like to use amin variable to slice the volume in the same way np.min would do:



    grid = np.indices(min.shape)
    idcs = np.stack([grid[0], grid[1], min])

    fmin = foo[idcs[0], idcs[1], idcs[2]]


    problem is that i can't use np.min because i also need the amin neighbors for interpolation reasons, something that i would obtain doing:



    pre  = foo[idcs[0], idcs[1], np.clip(idcs[2]-1, 0, 9)]
    post = foo[idcs[0], idcs[1], np.clip(idcs[2]+1, 0, 9)]


    Is there a more pythonic (nupyic) way to do this without creating an np.grid? something like:



    foo[:,:,amin-1:amin+1]


    that actually works (i would care about margin handling with an early-padding)










    share|improve this question



























      3












      3








      3








      I have a 3D numpy volume and a 2D numpy matrix:



      foo = np.random.rand(20,20,10)
      amin = np.argmin(foo, axis=2)


      i would like to use amin variable to slice the volume in the same way np.min would do:



      grid = np.indices(min.shape)
      idcs = np.stack([grid[0], grid[1], min])

      fmin = foo[idcs[0], idcs[1], idcs[2]]


      problem is that i can't use np.min because i also need the amin neighbors for interpolation reasons, something that i would obtain doing:



      pre  = foo[idcs[0], idcs[1], np.clip(idcs[2]-1, 0, 9)]
      post = foo[idcs[0], idcs[1], np.clip(idcs[2]+1, 0, 9)]


      Is there a more pythonic (nupyic) way to do this without creating an np.grid? something like:



      foo[:,:,amin-1:amin+1]


      that actually works (i would care about margin handling with an early-padding)










      share|improve this question
















      I have a 3D numpy volume and a 2D numpy matrix:



      foo = np.random.rand(20,20,10)
      amin = np.argmin(foo, axis=2)


      i would like to use amin variable to slice the volume in the same way np.min would do:



      grid = np.indices(min.shape)
      idcs = np.stack([grid[0], grid[1], min])

      fmin = foo[idcs[0], idcs[1], idcs[2]]


      problem is that i can't use np.min because i also need the amin neighbors for interpolation reasons, something that i would obtain doing:



      pre  = foo[idcs[0], idcs[1], np.clip(idcs[2]-1, 0, 9)]
      post = foo[idcs[0], idcs[1], np.clip(idcs[2]+1, 0, 9)]


      Is there a more pythonic (nupyic) way to do this without creating an np.grid? something like:



      foo[:,:,amin-1:amin+1]


      that actually works (i would care about margin handling with an early-padding)







      python numpy






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 28 '18 at 13:34







      Luca

















      asked Nov 28 '18 at 13:20









      LucaLuca

      69711029




      69711029
























          1 Answer
          1






          active

          oldest

          votes


















          2














          You could use np.ogrid instead of np.indices to save memory.
          np.ogrid returns an "open" meshgrid:



          In [24]: np.ogrid[:5,:5]
          Out[24]:
          [array([[0],
          [1],
          [2],
          [3],
          [4]]), array([[0, 1, 2, 3, 4]])]


          ogrid returns component arrays which can be used as indices
          in the same way as one would use np.indices.
          NumPy will automatically broadcast the values in the open mesh when they are used as indices:



          In [49]: (np.indices((5,5)) == np.broadcast_arrays(*np.ogrid[:5, :5])).all()
          Out[49]: True




          import numpy as np
          h, w, d = 20, 20, 10
          foo = np.random.rand(h, w, d)
          amin = np.argmin(foo, axis=2)
          X, Y = np.ogrid[:h, :w]
          amins = np.stack([np.clip(amin+i, 0, d-1) for i in [-1, 0, 1]])
          fmins = foo[X, Y, amins]


          It's better to store fmin, pre and post in one array, fmins,
          since some NumPy/Scipy operations (like argmin or griddata) may need the values in one array. If, later, you need to operate on the 3 components individually, you can always access them using fmins[i] or define



          pre, fmin, post = fmins





          share|improve this answer


























          • I like your answer, if nobody come up with anything better i will mark as answer

            – Luca
            Nov 28 '18 at 13:59






          • 1





            Shouldn't it be np.clip(amin+i, ..., so you get amin - 1, amin, amin + 1?

            – jdehesa
            Nov 28 '18 at 14:16











          • @jdehesa well, it depends on the definiton of pre and post, the way you say is the one i was searching for

            – Luca
            Nov 28 '18 at 14:19













          • @jdehesa: Thanks for the correction.

            – unutbu
            Nov 28 '18 at 14:24











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53520411%2fnumpy-slicing-a-volume-using-a-matrix%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          You could use np.ogrid instead of np.indices to save memory.
          np.ogrid returns an "open" meshgrid:



          In [24]: np.ogrid[:5,:5]
          Out[24]:
          [array([[0],
          [1],
          [2],
          [3],
          [4]]), array([[0, 1, 2, 3, 4]])]


          ogrid returns component arrays which can be used as indices
          in the same way as one would use np.indices.
          NumPy will automatically broadcast the values in the open mesh when they are used as indices:



          In [49]: (np.indices((5,5)) == np.broadcast_arrays(*np.ogrid[:5, :5])).all()
          Out[49]: True




          import numpy as np
          h, w, d = 20, 20, 10
          foo = np.random.rand(h, w, d)
          amin = np.argmin(foo, axis=2)
          X, Y = np.ogrid[:h, :w]
          amins = np.stack([np.clip(amin+i, 0, d-1) for i in [-1, 0, 1]])
          fmins = foo[X, Y, amins]


          It's better to store fmin, pre and post in one array, fmins,
          since some NumPy/Scipy operations (like argmin or griddata) may need the values in one array. If, later, you need to operate on the 3 components individually, you can always access them using fmins[i] or define



          pre, fmin, post = fmins





          share|improve this answer


























          • I like your answer, if nobody come up with anything better i will mark as answer

            – Luca
            Nov 28 '18 at 13:59






          • 1





            Shouldn't it be np.clip(amin+i, ..., so you get amin - 1, amin, amin + 1?

            – jdehesa
            Nov 28 '18 at 14:16











          • @jdehesa well, it depends on the definiton of pre and post, the way you say is the one i was searching for

            – Luca
            Nov 28 '18 at 14:19













          • @jdehesa: Thanks for the correction.

            – unutbu
            Nov 28 '18 at 14:24
















          2














          You could use np.ogrid instead of np.indices to save memory.
          np.ogrid returns an "open" meshgrid:



          In [24]: np.ogrid[:5,:5]
          Out[24]:
          [array([[0],
          [1],
          [2],
          [3],
          [4]]), array([[0, 1, 2, 3, 4]])]


          ogrid returns component arrays which can be used as indices
          in the same way as one would use np.indices.
          NumPy will automatically broadcast the values in the open mesh when they are used as indices:



          In [49]: (np.indices((5,5)) == np.broadcast_arrays(*np.ogrid[:5, :5])).all()
          Out[49]: True




          import numpy as np
          h, w, d = 20, 20, 10
          foo = np.random.rand(h, w, d)
          amin = np.argmin(foo, axis=2)
          X, Y = np.ogrid[:h, :w]
          amins = np.stack([np.clip(amin+i, 0, d-1) for i in [-1, 0, 1]])
          fmins = foo[X, Y, amins]


          It's better to store fmin, pre and post in one array, fmins,
          since some NumPy/Scipy operations (like argmin or griddata) may need the values in one array. If, later, you need to operate on the 3 components individually, you can always access them using fmins[i] or define



          pre, fmin, post = fmins





          share|improve this answer


























          • I like your answer, if nobody come up with anything better i will mark as answer

            – Luca
            Nov 28 '18 at 13:59






          • 1





            Shouldn't it be np.clip(amin+i, ..., so you get amin - 1, amin, amin + 1?

            – jdehesa
            Nov 28 '18 at 14:16











          • @jdehesa well, it depends on the definiton of pre and post, the way you say is the one i was searching for

            – Luca
            Nov 28 '18 at 14:19













          • @jdehesa: Thanks for the correction.

            – unutbu
            Nov 28 '18 at 14:24














          2












          2








          2







          You could use np.ogrid instead of np.indices to save memory.
          np.ogrid returns an "open" meshgrid:



          In [24]: np.ogrid[:5,:5]
          Out[24]:
          [array([[0],
          [1],
          [2],
          [3],
          [4]]), array([[0, 1, 2, 3, 4]])]


          ogrid returns component arrays which can be used as indices
          in the same way as one would use np.indices.
          NumPy will automatically broadcast the values in the open mesh when they are used as indices:



          In [49]: (np.indices((5,5)) == np.broadcast_arrays(*np.ogrid[:5, :5])).all()
          Out[49]: True




          import numpy as np
          h, w, d = 20, 20, 10
          foo = np.random.rand(h, w, d)
          amin = np.argmin(foo, axis=2)
          X, Y = np.ogrid[:h, :w]
          amins = np.stack([np.clip(amin+i, 0, d-1) for i in [-1, 0, 1]])
          fmins = foo[X, Y, amins]


          It's better to store fmin, pre and post in one array, fmins,
          since some NumPy/Scipy operations (like argmin or griddata) may need the values in one array. If, later, you need to operate on the 3 components individually, you can always access them using fmins[i] or define



          pre, fmin, post = fmins





          share|improve this answer















          You could use np.ogrid instead of np.indices to save memory.
          np.ogrid returns an "open" meshgrid:



          In [24]: np.ogrid[:5,:5]
          Out[24]:
          [array([[0],
          [1],
          [2],
          [3],
          [4]]), array([[0, 1, 2, 3, 4]])]


          ogrid returns component arrays which can be used as indices
          in the same way as one would use np.indices.
          NumPy will automatically broadcast the values in the open mesh when they are used as indices:



          In [49]: (np.indices((5,5)) == np.broadcast_arrays(*np.ogrid[:5, :5])).all()
          Out[49]: True




          import numpy as np
          h, w, d = 20, 20, 10
          foo = np.random.rand(h, w, d)
          amin = np.argmin(foo, axis=2)
          X, Y = np.ogrid[:h, :w]
          amins = np.stack([np.clip(amin+i, 0, d-1) for i in [-1, 0, 1]])
          fmins = foo[X, Y, amins]


          It's better to store fmin, pre and post in one array, fmins,
          since some NumPy/Scipy operations (like argmin or griddata) may need the values in one array. If, later, you need to operate on the 3 components individually, you can always access them using fmins[i] or define



          pre, fmin, post = fmins






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 28 '18 at 14:24

























          answered Nov 28 '18 at 13:55









          unutbuunutbu

          559k10512041257




          559k10512041257













          • I like your answer, if nobody come up with anything better i will mark as answer

            – Luca
            Nov 28 '18 at 13:59






          • 1





            Shouldn't it be np.clip(amin+i, ..., so you get amin - 1, amin, amin + 1?

            – jdehesa
            Nov 28 '18 at 14:16











          • @jdehesa well, it depends on the definiton of pre and post, the way you say is the one i was searching for

            – Luca
            Nov 28 '18 at 14:19













          • @jdehesa: Thanks for the correction.

            – unutbu
            Nov 28 '18 at 14:24



















          • I like your answer, if nobody come up with anything better i will mark as answer

            – Luca
            Nov 28 '18 at 13:59






          • 1





            Shouldn't it be np.clip(amin+i, ..., so you get amin - 1, amin, amin + 1?

            – jdehesa
            Nov 28 '18 at 14:16











          • @jdehesa well, it depends on the definiton of pre and post, the way you say is the one i was searching for

            – Luca
            Nov 28 '18 at 14:19













          • @jdehesa: Thanks for the correction.

            – unutbu
            Nov 28 '18 at 14:24

















          I like your answer, if nobody come up with anything better i will mark as answer

          – Luca
          Nov 28 '18 at 13:59





          I like your answer, if nobody come up with anything better i will mark as answer

          – Luca
          Nov 28 '18 at 13:59




          1




          1





          Shouldn't it be np.clip(amin+i, ..., so you get amin - 1, amin, amin + 1?

          – jdehesa
          Nov 28 '18 at 14:16





          Shouldn't it be np.clip(amin+i, ..., so you get amin - 1, amin, amin + 1?

          – jdehesa
          Nov 28 '18 at 14:16













          @jdehesa well, it depends on the definiton of pre and post, the way you say is the one i was searching for

          – Luca
          Nov 28 '18 at 14:19







          @jdehesa well, it depends on the definiton of pre and post, the way you say is the one i was searching for

          – Luca
          Nov 28 '18 at 14:19















          @jdehesa: Thanks for the correction.

          – unutbu
          Nov 28 '18 at 14:24





          @jdehesa: Thanks for the correction.

          – unutbu
          Nov 28 '18 at 14:24




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53520411%2fnumpy-slicing-a-volume-using-a-matrix%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Contact image not getting when fetch all contact list from iPhone by CNContact

          count number of partitions of a set with n elements into k subsets

          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks