Last active
August 29, 2015 14:18
-
-
Save Holzhaus/998f0113b09f7ba77248 to your computer and use it in GitHub Desktop.
Cell Scan Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
cell-scan-conv.py - A simple script to mass convert images while keeping only | |
some of the RGB channels to make cells more visible on cell | |
scans. Please note that ImageMagick's convert command needs | |
to be installed and in your $PATH. | |
Copyright (c) 2015, Jan Holthuis | |
All rights reserved. | |
Redistribution and use in source and binary forms, with or without | |
modification, are permitted provided that the following conditions are met: | |
1. Redistributions of source code must retain the above copyright notice, this | |
list of conditions and the following disclaimer. | |
2. Redistributions in binary form must reproduce the above copyright notice, | |
this list of conditions and the following disclaimer in the documentation | |
and/or other materials provided with the distribution. | |
3. Neither the name of the copyright holder nor the names of its contributors | |
may be used to endorse or promote products derived from this software | |
without specific prior written permission. | |
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | |
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | |
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | |
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
""" | |
import logging | |
import sys | |
import os | |
import subprocess | |
import multiprocessing | |
import distutils.spawn | |
import argparse | |
IM_CONVERT_EXE = distutils.spawn.find_executable('convert') | |
if IM_CONVERT_EXE is None: | |
print('ERROR: ImageMagick convert not found') | |
sys.exit(1) | |
CHANNEL_RED = 1 # 0000 0001 | |
CHANNEL_GREEN = 2 # 0000 0010 | |
CHANNEL_BLUE = 4 # 0000 0100 | |
def copy_image_channels_to_img(src, dst, channels): | |
removed_channels = [] | |
if not channels & CHANNEL_RED: | |
removed_channels.append('Red') | |
if not channels & CHANNEL_GREEN: | |
removed_channels.append('Green') | |
if not channels & CHANNEL_BLUE: | |
removed_channels.append('Blue') | |
kept_channels = list(set(['Red', 'Green', 'Blue']) - set(removed_channels)) | |
logger = logging.getLogger(__name__) | |
if not kept_channels: | |
logger.error('Removing all channels from "%s" would result in a' + | |
'black image. Conversion canceled.', src) | |
return -1 | |
cmd = [IM_CONVERT_EXE, src] | |
if removed_channels: | |
cmd.extend(['-channel', ','.join(removed_channels), | |
'-evaluate', 'set', '0']) | |
cmd.append(dst) | |
status = subprocess.call(cmd) | |
if status != 0: | |
logger.error('Copying "%s" to "%s" while keeping channels {%s} ' + | |
'failed with status "%d"', src, dst, | |
', '.join(kept_channels), status) | |
else: | |
logger.info('Successfully copied "%s" to "%s" while keeping ' + | |
'channels {%s}!', src, dst, ', '.join(kept_channels)) | |
def make_channeldesc(channels): | |
channeldesc = '' | |
if channels & CHANNEL_RED: | |
channeldesc += 'R' | |
if channels & CHANNEL_GREEN: | |
channeldesc += 'G' | |
if channels & CHANNEL_BLUE: | |
channeldesc += 'B' | |
return channeldesc | |
def process_image(filepath): | |
path = os.path.dirname(filepath) | |
base = os.path.splitext(os.path.basename(filepath))[0] | |
for channels in [CHANNEL_BLUE, | |
CHANNEL_BLUE | CHANNEL_RED, | |
CHANNEL_BLUE | CHANNEL_GREEN]: | |
dst = os.path.join(path, | |
"%s_%s.tif" % (base, make_channeldesc(channels))) | |
copy_image_channels_to_img(filepath, dst, channels) | |
def gather_files(input_directory): | |
logger = logging.getLogger(__name__) | |
gathered_files = [] | |
for directory, dirs, files in os.walk(input_directory): | |
logger.info('Gathering files in "%s"...', directory) | |
for filename in files: | |
if filename.lower().endswith('.tif'): | |
gathered_files.append(os.path.join(directory, filename)) | |
logger.info('Gathered %d files for processing.', len(gathered_files)) | |
return gathered_files | |
def process_directory(directory, num_processes=4): | |
logger = logging.getLogger(__name__) | |
# First we gather the files | |
files = gather_files(directory) | |
num_files = len(files) | |
if num_files > 0: | |
num_chars = len(str(num_files)) | |
# Setting up the multiprocessing pool | |
pool = multiprocessing.Pool(processes=num_processes) | |
# Now let's process them | |
for i, filename in enumerate(files): | |
pool.apply(process_image, args=(filename,)) | |
logger.info('Processing %s/%d: %s', | |
str(i+1).zfill(num_chars), | |
num_files, | |
filename) | |
logger.info('Done.') | |
if __name__ == "__main__": | |
logging.basicConfig(level=logging.INFO) | |
parser = argparse.ArgumentParser( | |
prog='cell-scan-conv.py', | |
formatter_class=argparse.ArgumentDefaultsHelpFormatter) | |
parser.add_argument('-j', type=int, default=4, metavar='num_processes', | |
help='Number of processes to use') | |
parser.add_argument('directory', help='The directory to scan for files') | |
args = parser.parse_args() | |
process_directory(directory=args.directory, num_processes=args.j) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment