在ImageJ中使用Jython进行多线程处理

时间:2018-05-21 13:33:05

标签: multithreading jython imagej

我在ImageJ中使用Jython编写了一个图像分析管道。我有兴趣使用多线程来加速这个过程。基本上,管道处理多个图像(以相同的方式),我想同时处理图像。 我见过一个使用Python和多处理(Running python multiprocess for Image processing)的例子。这对Jython来说是不可能的。任何关于如何继续的帮助将非常感激(我对多线程是全新的)

2 个答案:

答案 0 :(得分:1)

Jython书的权威指南有一章关于并发性,它为这个问题提供了一个非常彻底的答案:

http://www.jython.org/jythonbook/en/1.0/Concurrency.html

答案 1 :(得分:0)

以下是我找到的解决方案,以防有用。注意 - 在我的计算机上,这并没有显着减少执行时间。

from java.util.concurrent import Callable
from java.util.concurrent import Executors, TimeUnit

# get user to select a directory and list all file names
settings = IJ.getDirectory("Choose a Directory")
for dirname, dirnames, filenames in os.walk(settings):
   for filename in filenames:
        SITES.append(os.path.join(dirname, filename))

# function for shutting down the pool - taken from: 
# http://www.jython.org/jythonbook/en/1.0/Concurrency.html
def shutdown_and_await_termination(pool, timeout):
  pool.shutdown()
  try:
    if not pool.awaitTermination(timeout, TimeUnit.SECONDS):
        pool.shutdownNow()
        if (not pool.awaitTermination(timeout, TimeUnit.SECONDS)):
            print >> sys.stderr, "Pool did not terminate"
  except InterruptedException, ex:
    # (Re-)Cancel if current thread also interrupted
    pool.shutdownNow()
    # Preserve interrupt status
    Thread.currentThread().interrupt()

# function that will change all images listed - in this case convert to 8bit
def help(imp):
  conv = ImageConverter(imp)
  conv.convertToGray8() 

# make a callable interface where image will be each image in the list
# in this case each image will be opened, the help function run, which 
# converts to 8bit and then the image is displayed on screen
class imageConverter(Callable):
  def __init__(self):
    self.test = image

  def call(self):
    imp = IJ.openImage(self.test)
    help(imp)
    imp.show()

# define the number of threads
MAX_CONCURRENT = 2
pool = Executors.newFixedThreadPool(MAX_CONCURRENT)
# define the task to do in a multithreaded way
imageConverter = [imageConverter() for image in SITES]

# use all defined threads to convert the images
pool.invokeAll(imageConverter)

shutdown_and_await_termination(pool, 5)