Code Monkey home page Code Monkey logo

read-roi's Introduction

read-roi

PyPI version Build Status codecov

Read ROI files .zip or .roi generated with ImageJ. Code is largely inspired from : http://rsb.info.nih.gov/ij/developer/source/ij/io/RoiDecoder.java.html

Functions

from read_roi import read_roi_file
from read_roi import read_roi_zip

roi = read_roi_file(roi_file_path)

# or

rois = read_roi_zip(roi_zip_path)

Note

  • Some format specifications are not implemented. See RoiDecoder.java for details.
  • Most of "normal" ROI files should work.
  • Feel free to hack it and send me modifications.

Requirements

  • Python 3.5 and above.

Install

pip install read-roi

Or you can use Anaconda and conda-forge:

conda config --add channels conda-forge
conda install read-roi

License

Under BSD license. See LICENSE.

Authors

Release a new version

  • Run tests: pytest -v read_roi/.
  • Install rever: conda install -y rever.
  • Run check: rever check.
  • Bump and release new version: rever VERSION_NUMBER.

read-roi's People

Contributors

ablot avatar hadim avatar scottclowe avatar swharden avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

read-roi's Issues

converting shapes to areas

Currently all ROIs (rectangle, polygon, oval, etc.) just report x/y coordinates of their edges. Do you have any plans to add a function to convert an ROI to area, which would output x,y pixel coordinates of all pixels inside the ROI?

This:

rois = read_roi_zip('RoiSet.zip')
for key in [x for x in rois.keys() if rois[x]['type'] is 'polygon']:
     print(key, rois[key]['type'], rois[key]['x'],rois[key]['y'])

Currently outputs:

0194-0028 polygon [19, 43, 39, 21, 13, 20] [179, 184, 202, 210, 194, 179]
0177-0225 polygon [220, 210, 208, 229, 243, 242] [165, 175, 186, 190, 187, 172]

But it would be great if:

print(rois[key]['area'])

...displayed a large list of all X/Y positions encircled by each shape. Each ROI dictionary would be pre-loaded with the area key when the data is read. Do you have code on hand that does this?

Resources:

New release

@scottclowe thanks for all the work.

I guess it makes sense to release a new version. Do you want to work one another PR?

If no then I'll wait for #20 to be merged and release a new version.

Polygon and freehand ROIs (partly) read in incorrectly

Hey,
I have been using your function to read cell outlines marked in ImageJ into my python pipeline without problems for a year now.
Now I moved to considerably larger images (10.000 x 10.000 pixels, before 1.000 x 1.000 pixels). I marked a couple of ROIs, saved as zip, and used the read_roi_zip() function to read. I got a weird pattern of errors:

-Some polygon ROIs are read in correctly.
-For some polygon ROIs, all x coordinates have a large negative offset (ca -60.000), while the y is correct
-With the freehand ROIs, I observed all four cases: correct ROIs, large negative offsets in x while y is ok, the reverse, and both x and y with large negative offsets.

I also found out that the following function from another github user works correctly on the same ROI file: https://github.com/tdsmith/ijroi

I attach my ROI file, a screenshot of the correct ROIs in Image J and the incorrectly read-in ROIs plotted in python.

image
First five coordinates of the read in ROIs (ID refers to legend in above figure).
Note that for all plots, I inverted the y coordinate to have the ROIs oriented as they are on the ImageJ screenshot below.

0 x [2104, 2302, 2573, 2729, 2833] 
  y [6647, 6605, 6428, 6251, 6167]
1 x [4709, 4063, 3875, 3844, 3646] 
  y [5073, 4751, 4615, 4417, 4313]
2 x [5605, 6032, 6345, 6522, 6741] 
  y [5521, 5834, 6032, 6188, 6428]
3 x [5188, 5199, 5167, 5240, 5334] 
  y [4928, 4844, 4761, 4709, 4709]
4 x [4844, 4678, 4553, 4553, 4542] 
  y [9126, 8897, 8720, 8616, 8397]
5 x [-57316, -57128, -57087, -57149, -57285] 
  y [4230, 4323, 4177, 4042, 4021]
6 x [-59066, -59108, -59108, -59108, -59108] 
  y [3334, 3365, 3386, 3396, 3406]
7 x [1583, 1541, 1531, 1521, 1510] 
  y [3907, 3907, 3907, 3907, 3907]
8 x [2062, 2104, 2115, 2115, 2135] 
  y [-57649, -57670, -57681, -57691, -57733]
9 x [-57431, -57472, -57493, -57504, -57514] 
  y [-57076, -57087, -57128, -57139, -57149]

image
image
image

Original ROIs in imageJ:

image

My code for plotting/reading in:

import original_read_roi
import matplotlib.pyplot as plt
import numpy as np
a = original_read_roi.read_roi_zip('hajdu_20180205_0_RBPMS_referenceROIs_day2_nozoom.zip')

for i,k in enumerate(list(a.keys())):
    plt.plot(np.array(a[k]['x']),-(np.array(a[k]['y'])),label=str(i))
    print(i,'x',a[k]['x'][:5],'\n  y',a[k]['y'][:5])
    
plt.title('all rois')
plt.legend(loc=6)
plt.show()

plt.figure(figsize=(10,10))

for i,k in enumerate(list(a.keys())):

    if a[k]['type']=='polygon':
        plt.plot(a[k]['x'],-(np.array(a[k]['y'])))
plt.title('polygon rois, uncorrected')
plt.show()
#
plt.figure(figsize=(10,10))

for i,k in enumerate(list(a.keys())):

    if a[k]['type']=='polygon':
        if a[k]['name']=='00005-04172-08334':
            plt.plot(np.array(a[k]['x'])+65307,-(np.array(a[k]['y'])),label='corrected outlier (added 65307 to y coordinate)')
        else:
            plt.plot(a[k]['x'],-(np.array(a[k]['y'])))
plt.title('polygon rois, corrected')
plt.legend()
plt.show()

for i,k in enumerate(list(a.keys())):

    if a[k]['type']=='freehand':
        
        plt.plot(np.array(a[k]['x']),-(np.array(a[k]['y'])),label=str(i))
        plt.title('only freehand rois')
plt.legend()
plt.show()

The ROI file used to obtain the above plots:
hajdu_20180205_0_RBPMS_referenceROIs_day2_nozoom.zip

I hope this helps to improve your code!
Cheers,
Jan.

Big values (above 32768) for Coordinates

Hello,

I just wanted to say that in large images, when one of the coordinates is larger than 32768 the integer passed to python is incorrect.

I just commented the following lines in the _read_roi.py file and it works for me:

if n >= 32768: # 215
n -= 65536 # 2
16

Please correct me if what i did can cause any problems

Adding save_rois function

Would it be simple to add a save_rois function that creates a .zip archive out of an ordered dictionary?

Thanks for this repo - it's come in really useful!

Add docstrings

It would be great if you could add docstrings to read_roi_file and read_roi_zip. That would make it a lot easier to work with the package.

an integer is required (got type str)

Hi,

I try to use your module but I got a error:

In [39]: read_roi_zip('11692a_x40_06_nuclei.tif.zip')

TypeError                                 Traceback (most recent call last)
<ipython-input-39-8b081d0c8add> in <module>()
----> 1 read_roi_zip('11692a_x40_06_nuclei.tif.zip')

/home/pi/Programs/anaconda2/envs/bioformats/lib/python2.7/site-packages/read_roi/_read_roi.pyc in read_roi_zip(zip_path)
    304     zf = zipfile.ZipFile(zip_path)
    305     for n in zf.namelist():
--> 306         rois.update(read_roi_file(zf.open(n)))
    307     return rois

/home/pi/Programs/anaconda2/envs/bioformats/lib/python2.7/site-packages/read_roi/_read_roi.pyc in read_roi_file(fpath)
    124 
    125     magic = get_byte(data, list(range(4)))
--> 126     magic = "".join([chr(c) for c in magic])
    127 
    128     # TODO: raise error if magic != 'Iout'

TypeError: an integer is required

11692a_x40_06_nuclei.tif.zip

The roi file was created by ImageJ, can you give me some hint where is the problem?

Cannot read in composite ROIs

In ImageJ, there can be ROIs of the type "composite". This will, for instance, be the case if several regions are marked in a single z-slice of a volume.

It looks like the current implementation of this package cannot read in those composites correctly. For me, it only returns a rectangle comprising the bounding box of the individual regions. I have not found a way to solve this issue.

However, a colleague wrote a small code snippet for Fiji as a workaround. This code snippet takes all composite ROIs and splits them up. Then, they can be processed with this package. If useful for you, please find the code below. Credits go to Mihail Todorov (LMU Munich):

// convert composite type ROIs for Python input
setBatchMode(true);
for (i=0; i<roiManager("count"); i++) { 
	roiManager("select", i);
	roiType=Roi.getType;
	if (roiType == "composite") {
		//print("type: "+roiType);
		roiManager("Split");
	}
  }
setBatchMode(false);
showMessage("Macro finished");

Small side note: Fiji/ImageJ for some reason requires to read in the data for which the ROI was defined in order to open/process the ROIs. Depending on the size of your data, this can be slow. We found that this works substantially faster if you just define a blank stack of 8 bit images of the same size.

TypeError: an integer is required when loading roi zip

Hello, I am running into the following error when trying to use the read_roi_zip function. Thanks in advance for your help!

TypeError                                 Traceback (most recent call last)
<ipython-input-283-4c2bc7a07df0> in <module>()
----> 1 read_roi_zip(r'D:\Ian\SLMValidation\GCL12\221130_GCL12_SLMtest\FOV1_allcells_RoiSet.zip')

C:\Users\Administrator\Anaconda\lib\site-packages\read_roi\_read_roi.pyc in read_roi_zip(zip_path)
    522     zf = zipfile.ZipFile(zip_path)
    523     for n in zf.namelist():
--> 524         rois.update(read_roi_file(zf.open(n)))
    525     return rois

C:\Users\Administrator\Anaconda\lib\site-packages\read_roi\_read_roi.pyc in read_roi_file(fpath)
    477     logging.debug("Read ROI for \"{}\"".format(name))
    478 
--> 479     roi, (hdr2Offset, n_coordinates, roi_type, channel, slice, frame, position, version, subtype, size) = extract_basic_roi_data(data)
    480     roi['name'] = name
    481 

C:\Users\Administrator\Anaconda\lib\site-packages\read_roi\_read_roi.pyc in extract_basic_roi_data(data)
    261 
    262     magic = get_byte(data, list(range(4)))
--> 263     magic = "".join([chr(c) for c in magic])
    264 
    265     # TODO: raise error if magic != 'Iout'

TypeError: an integer is required

unclosed ROIs are found

When I tried to recover the ROIs that I generated from the ImageJ, I found some of them are not closed. Example attached. The left is from ImageJ and the right is the one recovered using your codes. Appreciate if you can help this.
open_roi

Is it possible to add reading each ROI Group

Hi there, great package, easy to use, and it works!

Is there any chance you can add reading of each ROI Group? The 'Group' is set in the ROI manager using the 'properties' dialog.

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.