How to optimize numpy operation, applying 2D condition on 3 channel RGB image? The Next CEO of Stack OverflowDoes Python have a ternary conditional operator?Saving a Numpy array as an imageHow can the Euclidean distance be calculated with NumPy?How to print the full NumPy array, without truncation?How do I read CSV data into a record array in NumPy?How to access the ith column of a NumPy multidimensional array?How do I get indices of N maximum values in a NumPy array?How to add an extra column to a NumPy arrayHow to convert 2D float numpy array to 2D int numpy array?Apply Function foreach Pixel in Numpy Array

Is French Guiana a (hard) EU border?

Decide between Polyglossia and Babel for LuaLaTeX in 2019

How did Beeri the Hittite come up with naming his daughter Yehudit?

IC has pull-down resistors on SMBus lines?

What CSS properties can the br tag have?

Graph of the history of databases

How to avoid supervisors with prejudiced views?

I dug holes for my pergola too wide

Can you teleport closer to a creature you are Frightened of?

What day is it again?

Yu-Gi-Oh cards in Python 3

0-rank tensor vs vector in 1D

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

Strange use of "whether ... than ..." in official text

Is there a difference between "Fahrstuhl" and "Aufzug"?

Towers in the ocean; How deep can they be built?

Does higher Oxidation/ reduction potential translate to higher energy storage in battery?

Is a distribution that is normal, but highly skewed, considered Gaussian?

Traduction de « Life is a roller coaster »

Is there such a thing as a proper verb, like a proper noun?

What difference does it make using sed with/without whitespaces?

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact

Help/tips for a first time writer?

Can I board the first leg of the flight without having final country's visa?



How to optimize numpy operation, applying 2D condition on 3 channel RGB image?



The Next CEO of Stack OverflowDoes Python have a ternary conditional operator?Saving a Numpy array as an imageHow can the Euclidean distance be calculated with NumPy?How to print the full NumPy array, without truncation?How do I read CSV data into a record array in NumPy?How to access the ith column of a NumPy multidimensional array?How do I get indices of N maximum values in a NumPy array?How to add an extra column to a NumPy arrayHow to convert 2D float numpy array to 2D int numpy array?Apply Function foreach Pixel in Numpy Array










0















I am trying to apply a computation from 2D alpha image to 3 channeled RGB image. I need to update pixel intensity in each channel, based on respective pixel value in 2D alpha image. Below is one MWE I created to illustrate the concept.



MWE:



# test alpha 2D image
test_a1 = np.array([
[0, 0, 50],
[0, 0, 150],
[0, 0, 225]
])

# test 3 channel RGB image
test_ir1 = np.ones((3,3,3))

# getting indices of alpha where cond is satisfied
idx = np.unravel_index(np.where(test_a1.ravel()>0),test_a1.shape)
test_output = np.zeros_like(test_ir1)
n_idx = len(idx[0][0])

# applying computation on 3 channel RGB image only where cond is satisfied.
for i in range(n_idx):

# multiply only where test_a1 > 0
r_idx, c_idx = idx[0][0][i], idx[1][0][i]
test_output[r_idx,c_idx,0] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 0]
test_output[r_idx,c_idx,1] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 1]
test_output[r_idx,c_idx,2] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 2]

test_output = test_output.astype('uint8')
plt.imshow(test_output, vmin=0, vmax=3)


output:
enter image description here



I basically tried to find the indices in 2D alpha image, where condition is met, and tried to apply those indices to all channels of the image.



Is there a way to optimize above operation (not for channel looping)? I am specifically looking to avoid the for loop in the code, doing numpy for each index. It is ver slow for regular images.










share|improve this question




























    0















    I am trying to apply a computation from 2D alpha image to 3 channeled RGB image. I need to update pixel intensity in each channel, based on respective pixel value in 2D alpha image. Below is one MWE I created to illustrate the concept.



    MWE:



    # test alpha 2D image
    test_a1 = np.array([
    [0, 0, 50],
    [0, 0, 150],
    [0, 0, 225]
    ])

    # test 3 channel RGB image
    test_ir1 = np.ones((3,3,3))

    # getting indices of alpha where cond is satisfied
    idx = np.unravel_index(np.where(test_a1.ravel()>0),test_a1.shape)
    test_output = np.zeros_like(test_ir1)
    n_idx = len(idx[0][0])

    # applying computation on 3 channel RGB image only where cond is satisfied.
    for i in range(n_idx):

    # multiply only where test_a1 > 0
    r_idx, c_idx = idx[0][0][i], idx[1][0][i]
    test_output[r_idx,c_idx,0] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 0]
    test_output[r_idx,c_idx,1] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 1]
    test_output[r_idx,c_idx,2] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 2]

    test_output = test_output.astype('uint8')
    plt.imshow(test_output, vmin=0, vmax=3)


    output:
    enter image description here



    I basically tried to find the indices in 2D alpha image, where condition is met, and tried to apply those indices to all channels of the image.



    Is there a way to optimize above operation (not for channel looping)? I am specifically looking to avoid the for loop in the code, doing numpy for each index. It is ver slow for regular images.










    share|improve this question


























      0












      0








      0








      I am trying to apply a computation from 2D alpha image to 3 channeled RGB image. I need to update pixel intensity in each channel, based on respective pixel value in 2D alpha image. Below is one MWE I created to illustrate the concept.



      MWE:



      # test alpha 2D image
      test_a1 = np.array([
      [0, 0, 50],
      [0, 0, 150],
      [0, 0, 225]
      ])

      # test 3 channel RGB image
      test_ir1 = np.ones((3,3,3))

      # getting indices of alpha where cond is satisfied
      idx = np.unravel_index(np.where(test_a1.ravel()>0),test_a1.shape)
      test_output = np.zeros_like(test_ir1)
      n_idx = len(idx[0][0])

      # applying computation on 3 channel RGB image only where cond is satisfied.
      for i in range(n_idx):

      # multiply only where test_a1 > 0
      r_idx, c_idx = idx[0][0][i], idx[1][0][i]
      test_output[r_idx,c_idx,0] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 0]
      test_output[r_idx,c_idx,1] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 1]
      test_output[r_idx,c_idx,2] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 2]

      test_output = test_output.astype('uint8')
      plt.imshow(test_output, vmin=0, vmax=3)


      output:
      enter image description here



      I basically tried to find the indices in 2D alpha image, where condition is met, and tried to apply those indices to all channels of the image.



      Is there a way to optimize above operation (not for channel looping)? I am specifically looking to avoid the for loop in the code, doing numpy for each index. It is ver slow for regular images.










      share|improve this question
















      I am trying to apply a computation from 2D alpha image to 3 channeled RGB image. I need to update pixel intensity in each channel, based on respective pixel value in 2D alpha image. Below is one MWE I created to illustrate the concept.



      MWE:



      # test alpha 2D image
      test_a1 = np.array([
      [0, 0, 50],
      [0, 0, 150],
      [0, 0, 225]
      ])

      # test 3 channel RGB image
      test_ir1 = np.ones((3,3,3))

      # getting indices of alpha where cond is satisfied
      idx = np.unravel_index(np.where(test_a1.ravel()>0),test_a1.shape)
      test_output = np.zeros_like(test_ir1)
      n_idx = len(idx[0][0])

      # applying computation on 3 channel RGB image only where cond is satisfied.
      for i in range(n_idx):

      # multiply only where test_a1 > 0
      r_idx, c_idx = idx[0][0][i], idx[1][0][i]
      test_output[r_idx,c_idx,0] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 0]
      test_output[r_idx,c_idx,1] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 1]
      test_output[r_idx,c_idx,2] = test_a1[r_idx, c_idx] * test_ir1[r_idx, c_idx, 2]

      test_output = test_output.astype('uint8')
      plt.imshow(test_output, vmin=0, vmax=3)


      output:
      enter image description here



      I basically tried to find the indices in 2D alpha image, where condition is met, and tried to apply those indices to all channels of the image.



      Is there a way to optimize above operation (not for channel looping)? I am specifically looking to avoid the for loop in the code, doing numpy for each index. It is ver slow for regular images.







      python numpy slice numpy-ndarray






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 8 at 6:30







      Parthiban Rajendran

















      asked Mar 7 at 17:57









      Parthiban RajendranParthiban Rajendran

      167110




      167110






















          1 Answer
          1






          active

          oldest

          votes


















          0














          You might observe that:
          test_output = np.einsum('ij,ijk->ijk', test_a1, test_ir1)

          Not sure if this helps reformulate a slightly different MWE if this isnt precisely what you intend



          === edited ===



          I would still make use of einsum since it allows you a lot of control of vectorised multidimensional linear algebra.



          Provided you can reduce your operations to some mathematical description, for example:




          Where test_a1 is greater than zero, double the intensity of the pixels measured over each channel.




          Then you do that in the following way:



          mask = test_a1 > 0
          output = np.einsum('ij,ijk->ijk', mask, test_ir1) + test_ir1





          share|improve this answer

























          • thank you I am looking for a way to avoid for loop to do operation for each (r,c) indices. That is ill way of using numpy usually.

            – Parthiban Rajendran
            Mar 8 at 6:32











          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%2f55050110%2fhow-to-optimize-numpy-operation-applying-2d-condition-on-3-channel-rgb-image%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









          0














          You might observe that:
          test_output = np.einsum('ij,ijk->ijk', test_a1, test_ir1)

          Not sure if this helps reformulate a slightly different MWE if this isnt precisely what you intend



          === edited ===



          I would still make use of einsum since it allows you a lot of control of vectorised multidimensional linear algebra.



          Provided you can reduce your operations to some mathematical description, for example:




          Where test_a1 is greater than zero, double the intensity of the pixels measured over each channel.




          Then you do that in the following way:



          mask = test_a1 > 0
          output = np.einsum('ij,ijk->ijk', mask, test_ir1) + test_ir1





          share|improve this answer

























          • thank you I am looking for a way to avoid for loop to do operation for each (r,c) indices. That is ill way of using numpy usually.

            – Parthiban Rajendran
            Mar 8 at 6:32















          0














          You might observe that:
          test_output = np.einsum('ij,ijk->ijk', test_a1, test_ir1)

          Not sure if this helps reformulate a slightly different MWE if this isnt precisely what you intend



          === edited ===



          I would still make use of einsum since it allows you a lot of control of vectorised multidimensional linear algebra.



          Provided you can reduce your operations to some mathematical description, for example:




          Where test_a1 is greater than zero, double the intensity of the pixels measured over each channel.




          Then you do that in the following way:



          mask = test_a1 > 0
          output = np.einsum('ij,ijk->ijk', mask, test_ir1) + test_ir1





          share|improve this answer

























          • thank you I am looking for a way to avoid for loop to do operation for each (r,c) indices. That is ill way of using numpy usually.

            – Parthiban Rajendran
            Mar 8 at 6:32













          0












          0








          0







          You might observe that:
          test_output = np.einsum('ij,ijk->ijk', test_a1, test_ir1)

          Not sure if this helps reformulate a slightly different MWE if this isnt precisely what you intend



          === edited ===



          I would still make use of einsum since it allows you a lot of control of vectorised multidimensional linear algebra.



          Provided you can reduce your operations to some mathematical description, for example:




          Where test_a1 is greater than zero, double the intensity of the pixels measured over each channel.




          Then you do that in the following way:



          mask = test_a1 > 0
          output = np.einsum('ij,ijk->ijk', mask, test_ir1) + test_ir1





          share|improve this answer















          You might observe that:
          test_output = np.einsum('ij,ijk->ijk', test_a1, test_ir1)

          Not sure if this helps reformulate a slightly different MWE if this isnt precisely what you intend



          === edited ===



          I would still make use of einsum since it allows you a lot of control of vectorised multidimensional linear algebra.



          Provided you can reduce your operations to some mathematical description, for example:




          Where test_a1 is greater than zero, double the intensity of the pixels measured over each channel.




          Then you do that in the following way:



          mask = test_a1 > 0
          output = np.einsum('ij,ijk->ijk', mask, test_ir1) + test_ir1






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 8 at 8:00

























          answered Mar 7 at 18:29









          Attack68Attack68

          1,1431412




          1,1431412












          • thank you I am looking for a way to avoid for loop to do operation for each (r,c) indices. That is ill way of using numpy usually.

            – Parthiban Rajendran
            Mar 8 at 6:32

















          • thank you I am looking for a way to avoid for loop to do operation for each (r,c) indices. That is ill way of using numpy usually.

            – Parthiban Rajendran
            Mar 8 at 6:32
















          thank you I am looking for a way to avoid for loop to do operation for each (r,c) indices. That is ill way of using numpy usually.

          – Parthiban Rajendran
          Mar 8 at 6:32





          thank you I am looking for a way to avoid for loop to do operation for each (r,c) indices. That is ill way of using numpy usually.

          – Parthiban Rajendran
          Mar 8 at 6:32



















          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%2f55050110%2fhow-to-optimize-numpy-operation-applying-2d-condition-on-3-channel-rgb-image%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

          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved