21 Replies Latest reply on Jun 3, 2013 2:24 AM by JohnnyR007

    Photoshop - combine red and green channel images into a merged image?

    JohnnyR007 Level 1

      Hi,

       

      I am a developmental biologist carrying out experiments on a type of microscope known as a Confocal Laser Scanning Microscope (CSLM).  Basically, this is a microscope coupled to some lasers which allow fluorescently-labelled parts of a biological sample to be imaged in high detail.

       

      For each sample there will be a set of two images produced, named and numbered as follows:

       

      sample01_g.tif

      sample01_r.tif

       

      Each image represents one fluorescent wavelength and correspond to green ( g ) and red ( r ).  These images are in rgb colour.

       

      I want to produce a merge of these two channels to generate a new TIFF file such that:

       

      Green channel is taken from sample01_g.tif

      Red channel is taken from sample01_r.tif

       

      Which would show me how the different channels co-localise, or not.

       

      This is fine to do by hand in Photoshop, but takes a long time when you have a couple of hundred images to process.  So, what I would like to do is write a script that batch automates the process, like a droplet.  I have the process outlined below:

       

      1. Create a new RGB TIFF called sample01_merge.tif
      2. Take the green channel from sample01_g.tif and copy it to the green channel of sample01_merge.tif
      3. Take the red channel from sample01_r.tif and copy it to the red channel of sample01_merge.tif
      4. Save sample01_merge.tif into a folder named "Merged Images" on the desktop
      5. Close the opened images
      6. Go to next set of images –> sample02_g.tif and sample02_r.tif
      7. Create a new RGB TIFF called sample02_merge.tif....and go through step 2-6, untill the last set of images has been processed.

       

      I have never used script before and would love to learn, but I am making slow progress and would like to have this problem solved sooner than I will be able to do so by myself.  So... I was wondering if anyone could give me some advice on how to go about doing this?

       

      Any help will be greatly appreciated!

       

      I use a Mac Pro running OSX 10.8.3 and Photoshop CS6 Extended

       

      Best regards,

      John

        • 1. Re: Photoshop - combine red and green channel images into a merged image?
          c.pfaffenbichler Level 9

          Could you please post one or several sample pairs of images (jpgs would be fine, a this site does not allow tiffs)?

           

          Personally I would prefer foregoing copy/pasting and instead place the images and use the Blend if settings, then flatten etc.

          Would you prefer file-selection or folder-selection?

          • 2. Re: Photoshop - combine red and green channel images into a merged image?
            JohnnyR007 Level 1

            Here are some rough samples. I don't have the originals at home, but I hope it will do.

             

            I guess it doesn't matter but folder-selection would be great. As long as the final merged images are saved in another folder, preferably on the Finder desktop. Just for the sake of learning, then it would be great if you could create another script that incorporates a file-selection. But only if you have the time!

             

            Thanks for taking your time to help me out here. I really appreciated it!!!

             

            /John

            sample01_g.jpgsample01_r.jpgsample02_g.jpgsample02_r.jpg

            • 3. Re: Photoshop - combine red and green channel images into a merged image?
              charles badland Level 4

              Keep in mind that many journals now want double-labeled pics to be Green and Magenta (with white showing co-localization). This would add the extra step of copying data from Red channel and pasting into Blue channel. The result is more more accessible for the color blind (Protanopia and Dueteranopia).

               

              Also,  a script will have to identify files of same name ("sample1") and be written to extract correct channel (red data from "_r.tiff" and green data from "_g.tiff"). I don't script, but I would think that would take some work.

              My thought is maybe it would be easier to record an Action and, instead of extracting channel data, just combine the 2 pics as layers and set Blend Mode of upper layer to Screen. This would not be a totally automatic process, but would reduce work quite a bit on processing hundreds of images. Also, many Confocal scopes have image capture software that does this automatically. Yours does not?

               

               

              BTW,

              Here is an example of Red/Green vs Magenta/Green double label technique and the preview for colorblindness.

              color-aware.jpg

              • 4. Re: Photoshop - combine red and green channel images into a merged image?
                Muppet Mark Level 5

                I would merge the documents by name… If in this case you have 2 out of 3 you can make a blank file on the fly…? They are just combined in RGB order ain't they…

                 

                #target photoshop
                
                mergeRGB();
                
                function mergeRGB() {
                  function cTID(s) { return app.charIDToTypeID(s); };
                  function sTID(s) { return app.stringIDToTypeID(s); };
                
                
                    var desc28 = new ActionDescriptor();
                        var list2 = new ActionList();
                            var ref10 = new ActionReference();
                            ref10.putName( cTID('Dcmn'), "r.tif" );
                        list2.putReference( ref10 );
                            var ref11 = new ActionReference();
                            ref11.putName( cTID('Dcmn'), "g.tif" );
                        list2.putReference( ref11 );
                            var ref12 = new ActionReference();
                            ref12.putName( cTID('Dcmn'), "b.tif" );
                        list2.putReference( ref12 );
                    desc28.putList( cTID('null'), list2 );
                    desc28.putEnumerated( cTID('Md  '), cTID('ClrS'), cTID('RGBC') );
                    executeAction( cTID('MrgC'), desc28, DialogModes.NO );
                };
                

                 

                This I just recorded using the channels pallete… No layers or C&P

                • 5. Re: Photoshop - combine red and green channel images into a merged image?
                  JohnnyR007 Level 1

                  Thanks Charles for your ideas. In this case color blindness isn't an issue as the images won't be stored in any journals, so I don't consider that to be important.

                   

                  I would prefer a script that could automagically merge the images, because I have several hundreds and more to come. Otherwise I could have used your solution.

                  • 6. Re: Photoshop - combine red and green channel images into a merged image?
                    JohnnyR007 Level 1

                    Mark, I'm a complete newbie and have no experience with scripting Photoshop. How would I use your script? Is it a java-script that I call on via File - Script - Browse menu?

                    • 7. Re: Photoshop - combine red and green channel images into a merged image?
                      Muppet Mark Level 5

                      The above snippet is NOT a full script just a sample of how I would go about the merge channels portion of this…

                       

                      I've just added a few extra lines… and it works fine here…

                       

                      I noticed that you posted the same question in AppleScript forums too…

                       

                      It is possible to do it that too but most users here use Adobe's ExtendScript…

                       

                      You can copy n paste the snytax from here into the ESTK debugger to test it…

                       

                      ESTK is Extend Script Tool Kit… and that should be installed in you Utilities folder on the mac…

                       

                      The first 3 variables are the paths to my test files on the desktop…

                       

                      #target photoshop
                      
                      var redFile = File( Folder.desktop + '/testing_R.tif' );
                      var greenFile = File( Folder.desktop + '/testing_G.tif' );
                      var blueFile = File( Folder.desktop + '/testing_B.tif' );
                      
                      var redName = redFile.name;
                      var greenName = greenFile.name;
                      var blueName = blueFile.name;
                      
                      app.open( redFile );
                      app.open( greenFile );
                      app.open( blueFile );
                      
                      mergeRGB( redName, greenName, blueName );
                      
                      function mergeRGB( r, g, b ) {
                          function cTID(s) { return app.charIDToTypeID(s); };
                      
                              var desc28 = new ActionDescriptor();
                              var list2 = new ActionList();
                              var ref10 = new ActionReference();
                              ref10.putName( cTID('Dcmn'), r );
                              list2.putReference( ref10 );
                              var ref11 = new ActionReference();
                              ref11.putName( cTID('Dcmn'), g );
                              list2.putReference( ref11 );
                              var ref12 = new ActionReference();
                              ref12.putName( cTID('Dcmn'), b );
                              list2.putReference( ref12 );
                              desc28.putList( cTID('null'), list2 );
                              desc28.putEnumerated( cTID('Md  '), cTID('ClrS'), cTID('RGBC') );
                      
                          executeAction( cTID('MrgC'), desc28, DialogModes.NO );
                      };
                      
                      
                      • 8. Re: Photoshop - combine red and green channel images into a merged image?
                        JohnnyR007 Level 1

                        Yeah...I asked the question in the AppleScript forum because I didn't know that Photoshop was able to do it without an Applescript. I was then recommended to get help from the Adobe community instead.

                         

                        Thanks Mark for the script, I'll have a look at the ESTK debugger. I guess this will only work on 3 images at a time and not a hole batch of images?

                        • 9. Re: Photoshop - combine red and green channel images into a merged image?
                          Muppet Mark Level 5

                          Yes the snippet just opens the 3 files and merges them… You are only using 2 channels? What is in blue…?

                           

                          Getting all the tifs from a selected folder is no big deal… A loop to open R & G pairs all doable with script…

                           

                          A little more info on your file naming would be needed… ( the pattern that pairs them )

                          • 10. Re: Photoshop - combine red and green channel images into a merged image?
                            JohnnyR007 Level 1

                            There is no info in the blue channel. I created a blank (black) file and used it as the B channel, but it looks like the green and red channel looses a lot of its luminocity, using this method.

                             

                            The naming pattern looks like this:

                             

                            sample0001_b.tif

                            sample0001_g.tif

                            sample0001_r.tif

                            sample0002_b.tif

                            sample0002_g.tif

                            sample0002_r.tif

                            sample0003_b.tif

                            sample0003_g.tif

                            sample0003_r.tif

                            ....and so on!

                             

                            But that can be changed.

                             

                            Here's the original green channel image:

                            sample01_g.jpg

                             

                            and the red:

                            sample01_r.jpg

                             

                            And here's the result:

                            result.jpg

                            • 11. Re: Photoshop - combine red and green channel images into a merged image?
                              Michael L Hale Level 5

                              I think dealing with the names and image sets is the easy part of this.

                               

                              From looking at your sample images, they are not single channel images. Both the _r and _g have image data in all three channels. I think that is the reason you are seeing the loss of luminosity. If I open a red/green set, select the red image, then use applyImage to blend each of the green channels into the red image channels using lighten mode I get a image like this.

                              mergedApplyImage.jpg

                              Here is my version of what a script to do this task would look like. Note however that it is not finished. It doesn't do the merging because I am still not sure how you want that part done.

                               

                              // make sure background color is black
                              var black = new SolidColor();
                              black.rgb.hexValue = "000000";
                              app.backgroundColor = black;
                              // make a reference to the savedFolder
                              var savedFolder = new Folder('~/desktop/Merged Image');
                              // create the folder if it doesn't exists
                              if(!savedFolder.exists) savedFolder.create();
                              // get the source folder from the user and store in variable
                              var sourceFolder = Folder.selectDialog();
                              // make sure user selected a folder
                              if(sourceFolder != null){
                                  // get an array of red images and store in variable
                                  var sourceFiles = sourceFolder.getFiles(/_r\.tif$/i);
                                  // make a loop to process all found sets.
                                  for(var i = 0; i < sourceFiles.length;i++){
                                      var redName = sourceFiles[i].name;
                                      var greenName = redName.replace('_r','_g');
                                      var redImage = open(sourceFiles[i]);// open the red file and store reference to document
                                      var greenImage = open(new File(sourceFolder+'/'+greenName));// open the green file and store reference that document
                                      // create merged document.
                                      var mergedImage = app.documents.add(redImage.width, redImage.height, redImage.resolution, redName.replace(/_r\.tif$/i,'_merged.tif'), NewDocumentMode.RGB,DocumentFill.BACKGROUNDCOLOR ,1,redImage.bitsPerChannel);
                                      /*  merge the other open documents into mergedImage
                                          maybe using applyImage
                                          first doc using normal mode
                                          other doc using lighten moce
                                          what about other channels
                                          */
                                      // make sure mergedImage is the active document incase the merge code switched documents
                                      app.activeDocument = mergedImage;
                                      // save the merged document
                                      SaveAsTiff(savedFolder+'/'+mergedImage.nam,true);
                                      // close the open documents for next loop
                                      redImage.close(SaveOptions.DONOTSAVECHANGES);
                                      greenImage.close(SaveOptions.DONOTSAVECHANGES);
                                      mergedImage.close(SaveOptions.DONOTSAVECHANGES);
                                      }
                              }
                              
                              
                              function SaveAsTIFF( inFileName, inLZW ) {
                                  var tiffSaveOptions = new TiffSaveOptions();
                                  if ( inLZW ) {
                                      tiffSaveOptions.imageCompression = TIFFEncoding.TIFFLZW;
                                  } else {
                                      tiffSaveOptions.imageCompression = TIFFEncoding.NONE;
                                  } 
                                  app.activeDocument.saveAs( File( inFileName ), tiffSaveOptions );
                              }
                              
                              • 12. Re: Photoshop - combine red and green channel images into a merged image?
                                JohnnyR007 Level 1

                                Hi Michael,

                                 

                                You're right about that it is not a single channel images, all of the images are stored as RGB with almost no info in the other channels (from what I can see).

                                 

                                The result you came up with seems to be spot on, but I wasn't able to run it on the few samples I have here at home. Simply because the script doesn't seem to save any images in the Merged Image folder it creates. It would be really interesting to run the script on a large batch of samples at work to see how the script performs. Would it be possible for your script to just save the results as an RGB tiff image in the folder it creates on the desktop?

                                 

                                /John

                                • 13. Re: Photoshop - combine red and green channel images into a merged image?
                                  Michael L Hale Level 5

                                  Yes, as I said it wasn't finished and wasn't meant to be used. It was just to show that working with image sets based on a name pattern is easy.

                                  Here is a version that does do the merge and save using applyImage.

                                   

                                  Note: for applyImage to work the images in each set need to be the same size. Some of your jpeg samples were not. This worked with one set by not the other.

                                   

                                  // make a reference to the savedFolder
                                  var savedFolder = new Folder('~/desktop/Merged Image');
                                  // create the folder if it doesn't exists
                                  if(!savedFolder.exists) savedFolder.create();
                                  // get the source folder from the user and store in variable
                                  var sourceFolder = Folder.selectDialog();
                                  // make sure user selected a folder
                                  if(sourceFolder != null){
                                      // get an array of red images and store in variable
                                      var sourceFiles = sourceFolder.getFiles(/_r\.tif$/i);
                                      // make a loop to process all found sets.
                                      for(var i = 0; i < sourceFiles.length;i++){
                                          var redName = sourceFiles[i].name;
                                          var greenName = redName.replace('_r','_g');
                                          var redImage = open(sourceFiles[i]);// open the red file and store reference to document
                                          var greenImage = open(new File(sourceFolder+'/'+greenName));// open the green file and store reference that document
                                          // now select each channel and apply matching channel in redImge using lighten mode
                                          app.activeDocument.activeChannels = [app.activeDocument.channels.getByName(localize('$$$/ColorModes/RGB/ChannelName/Red=Red'))];
                                          applyChannel( charIDToTypeID( "Rd  " ), redImage.name );
                                          app.activeDocument.activeChannels = [app.activeDocument.channels.getByName(localize('$$$/ColorModes/RGB/ChannelName/Green=Green'))];
                                          applyChannel( charIDToTypeID( "Grn " ), redImage.name );
                                          app.activeDocument.activeChannels = [app.activeDocument.channels.getByName(localize('$$$/ColorModes/RGB/ChannelName/Blue=Blue'))];
                                          applyChannel( charIDToTypeID( "Bl  " ), redImage.name );
                                          // select the componet channel( rgb )
                                          selectComponentChannel();
                                          // save the merged document
                                          SaveAsTIFF(savedFolder+'/'+redName.replace(/_r\.tif$/i,'_merged.tif'),true);
                                          // close the open documents for next loop
                                          redImage.close(SaveOptions.DONOTSAVECHANGES);
                                          greenImage.close(SaveOptions.DONOTSAVECHANGES);
                                          }
                                  }
                                  function applyChannel( channelID, documentName ){
                                      // charIDToTypeID( "Rd  " )
                                      // charIDToTypeID( "Grn " )
                                      // charIDToTypeID( "Bl  " )
                                      var desc = new ActionDescriptor();
                                      var channelsDesc = new ActionDescriptor();
                                      var ref = new ActionReference();
                                      ref.putEnumerated( charIDToTypeID( "Chnl" ), charIDToTypeID( "Chnl" ), channelID);
                                      ref.putProperty( charIDToTypeID( "Lyr " ), charIDToTypeID( "Bckg" ) );
                                      ref.putName( charIDToTypeID( "Dcmn" ), documentName );
                                      channelsDesc.putReference( charIDToTypeID( "T   " ), ref );
                                      channelsDesc.putEnumerated( charIDToTypeID( "Clcl" ), charIDToTypeID( "Clcn" ), charIDToTypeID( "Lghn" ) );
                                      channelsDesc.putBoolean( charIDToTypeID( "PrsT" ), true );
                                      desc.putObject( charIDToTypeID( "With" ), charIDToTypeID( "Clcl" ), channelsDesc );
                                      executeAction( charIDToTypeID( "AppI" ), desc, DialogModes.NO );
                                  };
                                  function SaveAsTIFF( inFileName, inLZW ) {
                                      var tiffSaveOptions = new TiffSaveOptions();
                                      if ( inLZW ) {
                                          tiffSaveOptions.imageCompression = TIFFEncoding.TIFFLZW;
                                      } else {
                                          tiffSaveOptions.imageCompression = TIFFEncoding.NONE;
                                      } 
                                      app.activeDocument.saveAs( File( inFileName ), tiffSaveOptions );
                                  };
                                  function selectComponentChannel() {
                                      try{
                                          var map = {}
                                          map[DocumentMode.GRAYSCALE] = charIDToTypeID('Blck');
                                          map[DocumentMode.RGB] = charIDToTypeID('RGB ');
                                          map[DocumentMode.CMYK] = charIDToTypeID('CMYK');
                                          map[DocumentMode.LAB] = charIDToTypeID('Lab ');
                                          var desc = new ActionDescriptor();
                                              var ref = new ActionReference();
                                              ref.putEnumerated( charIDToTypeID('Chnl'), charIDToTypeID('Chnl'), map[app.activeDocument.mode] );
                                          desc.putReference( charIDToTypeID('null'), ref );
                                          executeAction( charIDToTypeID('slct'), desc, DialogModes.NO );
                                      }catch(e){}
                                  };
                                  
                                  • 14. Re: Photoshop - combine red and green channel images into a merged image?
                                    JohnnyR007 Level 1

                                    Thanks Michael for helping me out here, I really appreciate it!

                                     

                                    I misunderstood you, I thought the script would  save the merged images.

                                     

                                    I tried the new version of your script on a folder containing just two images from the same set, one red and one green – both the exact same size in pixels. The script creates the folder on the desktop but doesn't save anything in it. I ran the script through ESTK debugger and also as a .jsx file from within Photoshop. I also tried it with a third image acting as the blue channel, with no info in any channels at all, but that didn't work either.

                                     

                                    Do you have any idea why it's not working here?

                                     

                                    /John

                                    • 15. Re: Photoshop - combine red and green channel images into a merged image?
                                      Michael L Hale Level 5

                                      I am not sure why it doesn't work for you. It is working here as long as the sets are the same size. If they are not it alerts an error when it tries to apply the miss-matched channels.

                                       

                                      Do you get any error messages? Can you post a link to where I can download tiff samples? If you are not getting error messages it should at least save the merged file even if it isn't merged as you wished. It is saving to the desktop so user permissions shouldn't be the problem. So there may be something about your source images that I missed.

                                       

                                      You can comment out one of the close lines like this.

                                       

                                      // greenImage.close(SaveOptions.DONOTSAVECHANGES);

                                       

                                      That will leave the merged document from each set open. When I run the script here using the jpg samples I get two merged documents when the script is finished running.

                                      • 16. Re: Photoshop - combine red and green channel images into a merged image?
                                        JohnnyR007 Level 1

                                        I restarted my Mac at home and then I discovered my mistake. The files I tried your script on was in fact jpg and not tif files and after converting them to tif your script worked just perfect (obviously). Sorry about that, I should have seen that.

                                         

                                        Thank you so much for your kind help. I'll try your script on a larger batch of sets first thing monday morning when I get back to work and let you know.

                                         

                                        Have a great weekend!

                                         

                                        /John

                                        • 17. Re: Photoshop - combine red and green channel images into a merged image?
                                          Michael L Hale Level 5

                                          If you are happy with the apply channel in lighten mode approach to blending the images this script does the same in fewer steps and should run faster.

                                           

                                          // make a reference to the savedFolder
                                          var savedFolder = new Folder('~/desktop/Merged Image');
                                          // create the folder if it doesn't exists
                                          if(!savedFolder.exists) savedFolder.create();
                                          // get the source folder from the user and store in variable
                                          var sourceFolder = Folder.selectDialog();
                                          // make sure user selected a folder
                                          if(sourceFolder != null){
                                              // get an array of red images and store in variable
                                              var sourceFiles = sourceFolder.getFiles(/_r\.tif$/i);
                                              // make a loop to process all found sets.
                                              for(var i = 0; i < sourceFiles.length;i++){
                                                  var redName = sourceFiles[i].name;
                                                  var greenName = redName.replace('_r','_g');
                                                  var redImage = open(sourceFiles[i]);// open the red file and store reference to document
                                                  var greenImage = open(new File(sourceFolder+'/'+greenName));// open the green file and store reference that document
                                                  // now apply redImge using lighten mode
                                                  applyChannel( charIDToTypeID( "RGB " ) , redImage.name );
                                                  // save the merged document
                                                  SaveAsTIFF(savedFolder+'/'+redName.replace(/_r\.tif$/i,'_merged.tif'),true);
                                                  // close the open documents for next loop
                                                  redImage.close(SaveOptions.DONOTSAVECHANGES);
                                                  greenImage.close(SaveOptions.DONOTSAVECHANGES);
                                                  }
                                          }
                                          function applyChannel( channelID, documentName ){
                                              // charIDToTypeID( "RGB " )
                                              // charIDToTypeID( "Rd  " )
                                              // charIDToTypeID( "Grn " )
                                              // charIDToTypeID( "Bl  " )
                                              var desc = new ActionDescriptor();
                                              var channelsDesc = new ActionDescriptor();
                                              var ref = new ActionReference();
                                              ref.putEnumerated( charIDToTypeID( "Chnl" ), charIDToTypeID( "Chnl" ), channelID);
                                              ref.putProperty( charIDToTypeID( "Lyr " ), charIDToTypeID( "Bckg" ) );
                                              ref.putName( charIDToTypeID( "Dcmn" ), documentName );
                                              channelsDesc.putReference( charIDToTypeID( "T   " ), ref );
                                              channelsDesc.putEnumerated( charIDToTypeID( "Clcl" ), charIDToTypeID( "Clcn" ), charIDToTypeID( "Lghn" ) );
                                              channelsDesc.putBoolean( charIDToTypeID( "PrsT" ), true );
                                              desc.putObject( charIDToTypeID( "With" ), charIDToTypeID( "Clcl" ), channelsDesc );
                                              executeAction( charIDToTypeID( "AppI" ), desc, DialogModes.NO );
                                          };
                                          function SaveAsTIFF( inFileName, inLZW ) {
                                              var tiffSaveOptions = new TiffSaveOptions();
                                              if ( inLZW ) {
                                                  tiffSaveOptions.imageCompression = TIFFEncoding.TIFFLZW;
                                              } else {
                                                  tiffSaveOptions.imageCompression = TIFFEncoding.NONE;
                                              } 
                                              app.activeDocument.saveAs( File( inFileName ), tiffSaveOptions );
                                          };
                                          

                                          BTW: this can be edited to work with other file formats. It now only works with tiff files as I thought that was the format of your source image from you scope.

                                          • 18. Re: Photoshop - combine red and green channel images into a merged image?
                                            JohnnyR007 Level 1

                                            Thanks Michael! - I'll try both script on a larger sets of tifs with higher resolution and see which works best for me. I'll let you know on monday!

                                             

                                            /John

                                            • 19. Re: Photoshop - combine red and green channel images into a merged image?
                                              Michael L Hale Level 5

                                              So we are clear. The two scripts do the same blending so the results will be the same. The difference is one blends one channel at a time and the other blends all three at once. I would recommend only using the second script to confirm you are happy with the way the image are blended. The first would only be slower without any improvement in the output.

                                               

                                              The first script would only be useful if you are unhappy with the results and want to try a different way of blending. Then the code for single channel blending might be helpful.

                                              • 21. Re: Photoshop - combine red and green channel images into a merged image?
                                                JohnnyR007 Level 1

                                                Hi Michael,

                                                 

                                                Your script worked perfectly! A ran the last and faster one and had no problems at all with 50 images.

                                                 

                                                Thank you Michael (and all the rest of you who helped me out).

                                                 

                                                Best regards,

                                                John