GithubHelp home page GithubHelp logo

jdoepfert / roipoly.py Goto Github PK

View Code? Open in Web Editor NEW
127.0 5.0 46.0 108 KB

Select a polygonal region of interest (ROI) with python and matplotlib, similar to the roipoly.m function from MATLAB.

License: Apache License 2.0

Python 91.71% Makefile 8.29%

roipoly.py's Introduction

https://travis-ci.org/jdoepfert/roipoly.py.svg?branch=master

roipoly.py

Small python module to select a polygonal region of interest (ROI) in an image that is stored as a numpy array. The usage is similar to the roipoly function present in the image processing toolbox from MATLAB.

/img/ROIs.PNG

Installation

Either from PyPi: pip install roipoly

Or get the latest version from github: pip install git+https://github.com/jdoepfert/roipoly.py

Running the examples

Basic usage:

python examples/basic_example.py

Drawing multiple ROIs:

python examples/multi_roi_example.py

Usage

Creating a ROI

In your python code, import the roipoly module using

from roipoly import RoiPoly

To draw a ROI within an image present as a numpy array, show it first using e.g. pylabs’s imshow:

from matplotlib import pyplot as plt
plt.imshow(image)

Then let the user draw a polygonal ROI within that image:

my_roi = RoiPoly(color='r') # draw new ROI in red color

This lets the user interactively draw a polygon within the image by clicking with the left mouse button to select the vertices of the polygon. To close the polygon, click with the right mouse button. After finishing the ROI, the current figure is closed so that the execution of the code can continue.

Displaying a ROI

To display a created ROI within an image, first display the image as described above using e.g. imshow. Then,

my_roi.display_roi()

shows the created ROI on top of this image.

Display multiple ROIs like so:

for r in [my_roi1, my_roi2, my_roi3]
    r.display_roi()

To additionally show the mean pixel grey value inside a ROI in the image, type

my_roi.display_mean(image)

Note that you can only pass 2D images to display_mean()! If you have e.g. an RGB-image with dimension 3, you need to make the call like so:

mask = my_roi.display_mean(rgb_image[:, :, 0])

Extracting a binary mask image

The function get_mask() creates a binary mask for a certain ROI instance, that is, a 2D numpy array of the size of the (2D) image array, whose elements are True if they lie inside the ROI polygon, and False otherwise.

mask = my_roi.get_mask(image)
plt.imshow(mask) # show the binary signal mask

Note that you can only pass 2D images to get_mask(), If you have e.g. an RGB-image with dimension 3, you need to make the call like so:

mask = my_roi.get_mask(rgb_image[:, :, 0])

The resulting mask image can then be used to e.g. calculate the mean pixel intensity in an image over that ROI:

mean = plt.mean(image[mask])

To get the ROI coordinates [(x1, y1), (x2, y2), …]:

roi_coordinates = my_roi.get_roi_coordinates()

Drawing multiple ROIs

See examples/multi_roi_example.py

Credits

Based on a code snippet originally posted here by Daniel Kornhauser.

roipoly.py's People

Contributors

georgedeath avatar jdoepfert avatar schmudo avatar venissacarolquadros avatar xksteven 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  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

roipoly.py's Issues

Example work

Hello,

I tried to run the basic example in spyder with anaconda. The roi choice works, but once I double click the code "freeze". It seems that if i try to close the kernel, the code is going to the next step and crash.

Thanks for your help !

How to install roipoly on windows

I am using python-3.6 with windows-7 64 bit installed. Can anyone please tell me how to install. I used pip to install but no use. :)

Enable option for drag-n-drop bounding boxes

Allowing this option of just clicking, dragging, and then releasing the click to create a bounding box would help those that need to quickly iterate through a lot of images and/or those that only need a rectangle ROI rather than a polygon.

cannot use the package because of deprecation

Now I am trying to install this package and run the basic_example, but when the picture shows, I when I click some point in the square, there is no response or red points to show the point.
It is said like that:
zhangqianlindeMacBook-Pro:roipoly.py zhangqianlin$ python3 examples/basic_example.py
/Users/zhangqianlin/anaconda3/lib/python3.7/site-packages/matplotlib/cbook/init.py:2349: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
if isinstance(obj, collections.Iterator):
/Users/zhangqianlin/anaconda3/lib/python3.7/site-packages/matplotlib/cbook/init.py:2366: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
return list(data) if isinstance(data, collections.MappingView) else data
Traceback (most recent call last):
File "examples/basic_example.py", line 29, in
roi1.display_roi()
File "/Users/zhangqianlin/anaconda3/lib/python3.7/site-packages/roipoly/roipoly.py", line 92, in display_roi
line = plt.Line2D(self.x + [self.x[0]], self.y + [self.y[0]],
IndexError: list index out of range

the version is python3.7 on the macOS.

LOOK FORWARD TO YOUR REPLY, THX!

example not work

I cloned the project from git and run it on my Mac.

I try to execute the basic_example.py but when the figure is shown it is not able to get my click so no figure is shown.

image

getMask() Does not work correctly with non-square images.

Lines 48 and 68 have the references to the dimension sizes the wrong way round, as python returns the y dimension before the x when using np.shape().

untitled

Changing line 48 to:
ny, nx = np.shape(currentImage)

and line 60 to:
grid = ROIpath.contains_points(points).reshape((ny,nx))

Fixes this issue.

untitled2

update CI pipeline

travis.org is outdated, use an up to date CI pipeline, e.g. travis.com

An alternative example for multiple roi regions

Hello!

The example provided in example.py demonstrates the use of roipoly.py for a single region of interest. However it would useful to also demo using it for multiple ROIs. I have created a script to demo this. But to get it to work I had to comment out the following lines from the end of roipoly.py:

if sys.flags.interactive:
    pass
else:
    #figure has to be closed so that code can continue
    print('closing')
    plt.close(self.fig) 

And the following script will create two buttons for multiple region selection unlimited.py:

# import pylab as pl
from matplotlib import pyplot as pl
from matplotlib.widgets import Button
import numpy as np
from roipoly import roipoly 

img = np.ones((100, 100)) * range(0, 100)
ROIs = []
fig = pl.Figure()
done = False

class Callback(object):
  has_next = True
  
  def addROI(self, event):

    # let user draw second ROI
    ROI = roipoly(roicolor='b') #let user draw ROI
    pl.show(block=False)

    # not sure why this is needed to be honest as the figure is
    # already being closed in the ROI class
    pl.close(ROI.fig)

    print('done with rois')
    ROIs.append(ROI)
    print(ROIs)

  def finish(self, event):
    global done
    global ROIs

    # # show ROI masks
    print(ROIs)
    print(len(ROIs))

    done = True
    # close the current figure
    pl.close(pl.gcf())


callback = Callback()

def initUI():
  # show the image
  pl.imshow(img, interpolation='nearest', cmap="Greys")
  pl.colorbar()
  pl.title("left click: line segment         right click: close region")

  pl.subplots_adjust(bottom=0.2)
  ax = pl.gca()
  axprev = pl.axes([0.7, 0.05, 0.1, 0.075])
  axnext = pl.axes([0.81, 0.05, 0.1, 0.075])
  bnext = Button(axnext, 'Add ROI')
  bnext.on_clicked(callback.addROI)
  bprev = Button(axprev, 'Finish')
  bprev.on_clicked(callback.finish)

  [x.displayROI() for x in ROIs]
  [x.displayMean(img) for x in ROIs]

  pl.show()


while not done:
  print(done)
  initUI()


if len(ROIs) >0:
  res = ROIs[0].getMask(img)
  for roi in ROIs:
    res = res + roi.getMask(img)

  pl.imshow(res, interpolation='nearest', cmap="Greys")
  pl.title('mask result')
  pl.show()

screen shot 2018-04-11 at 17 26 00

I'm sharing this to help other users that are using the library. Also happy to submit a PR if it's worthy of merging this example in the library

Cannot create a ROI twice

Hello,
I'm having a problem when using your library. The main code I'm using is this one:

def Load_Tiff():
    img = Image.open(filepath)
    
    """ We convert the RGB image in a gray image."""
    img.getdata()
    r, g, b = img.split()
    ra = np.array(r)
    ga = np.array(g)
    ba = np.array(b)
    

    global gray
    gray = (ra + ga + ba)
    Background_Mask()

def Background_Mask():
    pyplot.close('all')
    fig_b=pyplot.figure("Background Mask", clear=True)
    
    pyplot.imshow(gray,cmap="coolwarm")

    pyplot.title("Please, select the background ROI.")
    my_roi_back = RoiPoly(color='r', fig=fig_b) # draw new ROI in red color
    average = RoiPoly.get_mean_and_std(my_roi_back, gray)
    mean = average[0]
    mean_error = average[1]

When I run it once, it runs just fine. But the second time I run it, without closing the current figure window, python returns the following error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Usuario Principal\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "D:\NanoScience\Experiments\MyScripts_Python\Contrast\Optical_Contrast.py", line 85, in openFile
    Load_Tiff()
  File "D:\NanoScience\Experiments\MyScripts_Python\Contrast\Optical_Contrast.py", line 120, in Load_Tiff
    Background_Mask()
  File "D:\NanoScience\Experiments\MyScripts_Python\Contrast\Optical_Contrast.py", line 157, in Background_Mask
    average = RoiPoly.get_mean_and_std(my_roi_back,gray)
  File "C:\Users\Usuario Principal\AppData\Local\Programs\Python\Python310\lib\site-packages\roipoly\roipoly.py", line 131, in get_mean_and_std
    mask = self.get_mask(image)
  File "C:\Users\Usuario Principal\AppData\Local\Programs\Python\Python310\lib\site-packages\roipoly\roipoly.py", line 98, in get_mask
    poly_verts = ([(self.x[0], self.y[0])]
IndexError: list index out of range

It seems RoiPoly returns an empty ROI without displaying the image, so, the get_mean_and_std function fails.
If I manually close the figure window it works.

Thank you.

Not able to select ROI in Jupyter Notebook

I am not able to select polygonal region of interest after plt.imshow(image) in Jupyter Notebook. The region within image does not highlight to select the polygon region with RoiPoly(color='r').
Browser: Google Chrome

Using an image crash the app

When using any type of image instead of
img = pl.ones((100, 100)) * range(0, 100)

I used

img = pl.imread("path_to_img")
pl.imshow(img)

the first plot is working fine but when I plot the second one , it stop with runtime error

error

Causes Spyder to hang

Hello,

I am trying to use this on Spyder v4.1.4 running python v3.7.7. I'm fairly new to python so this might be a simple error on my part.

When I run your example, everything is going fine until I finish drawing my first ROI and right click. This closes the window but the code just hangs. If I interrupt the kernel it continues to hang and I need to restart the kernel. While it is restarting it then shows me the figure with my defined ROI (which looks great and is what I'm looking to achieve), but obviously I can't obtain the mask from that ROI and use it later in my code as I've had to restart everything. Have I configured something wrong to cause this hanging? This happens when I just run the code from your example (https://github.com/jdoepfert/roipoly.py/blob/master/examples/basic_example.py) without changing anything.

Cheers,
Matthew

List index out of range in display roi

when I opened a NumPY array of a grayscale image it shows the image and I am able to draw an ROI but it does not display an ROI ,I am using Python3 and the error is in line 65 of roipoly that list index is out of range, I am attching the snapshot of error:
errorroi

IndexError in display_roi

Hi,

I'm getting an IndexError when running basic_example.py. After completing my ROI (either by right click or double click) the script terminates abrutly without returning mask or values from the ROI. Traceback from script start below. Any ideas?

File C:\WinPython-3702\python-3.7.0.amd64\lib\site-packages\roipoly\roipoly.py, line 92, in display_roi

line = plt.Line2D(self.x + [self.x[0]], self.y + [self.y[0]],

IndexError: list index out of range

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.