imgbasics


Nameimgbasics JSON
Version 0.3.0 PyPI version JSON
download
home_pagehttps://github.com/ovinc/imgbasics
SummaryBasic image analysis tools (cropping, contour properties, etc.)
upload_time2023-01-30 16:38:34
maintainer
docs_urlNone
authorOlivier Vincent
requires_python>=3.6
licenseBSD 3-Clause License
keywords image analysis crop imcrop cropping contour contours centroid perimeter area
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            About
=====

Basic image analysis tools, with the following functions:

- `imcrop()`: image cropping, with interactive options,
- `contour_properties()`: calculate centroid, area, and perimeter of a contour,
- `closest_contour()`: closest contour to a position,
- `contour_coords()`: transform contour from scikit-image or opencv into usable x, y data,

The `imgbasics.transform` module also contains functions mimicking those found in Scikit Image's transform module, but that are based on OpenCV for improved speed. For now it only contains:

- `transform.rotate()`: rotate image

*Note*: the package also defines a `ContourError` class as a custom exception for errors in contour calculations.

Install
=======

```bash
pip install imgbasics
```

Quick start
===========

Below is some information to use available functions. Please also consult docstrings and the Jupyter notebooks **ExamplesBasics.ipynb** for more details and examples.


## Image cropping (`imcrop`)

Image cropping function; the interactive mode allows the user to define the region of interest on the image interactively, either using clicks or a draggable rectangle.

The image `img` is assumed to be already loaded in memory as a numpy array (or equivalent, i.e. that supports slicing and defines `shape` and `ndim` attributes)

### Non-interactive mode

```python
img_crop = imgbasics.imcrop(img, cropzone)
```
Crops the image `img` according to a pre-defined crop rectangle `cropzone = xmin, ymin, width, height`. Contrary to the Matlab imcrop function with the same name, the cropped image is really of the width and height requested in terms of number of pixels, not w+1 and h+1 as in Matlab.

### Interactive mode

```python
img_crop, cropzone = imgbasics.imcrop(img)
```
Cropping rectangle is drawn on the image (img) by either:
- defining two corners of the rectangle by clicking (default).
- using a draggable rectangle for selection and pressing "enter" (`draggable=True` option)

The returned cropzone corresponds to `xmin, ymin, width, height`.

*Note*: when selecting, the pixels taken into account are those which have
their centers closest to the click, not their edges closest to the click.
For example, to crop to a single pixel, one needs to click two times within
this pixel (possibly at the same location). For images with few pixels,
this results in a visible offset between the dotted lines plotted after the
clicks (running through the centers of the pixels clicked) and the final
rectangle, which runs along the edges of all pixels selected.

### Other arguments

Other arguments are available, e.g. for appearance, visibility, axes, etc. of the cropping tools. See docstrings for details.


## Contour properties (`contour_properties`)

Returns centroid position, perimeter and area of a contour as a dictionary with keys `'centroid'` (tuple with x and y position), `'perimeter'` (positive float), `'area'` (signed float). The sign convention for the area *A* differs depending on what type of plot is used (because `plt.imshow()` and `plt.plot()` do not use the same coordinate conventions):

| direction      |  imshow image (`plt.imshow()`)  | regular plot (`plt.plot()`)
| :---:          | :---:                           | :---:
| clockwise      |  *A* < 0  |  *A* > 0  |
| anti-clockwise |  *A* > 0  |  *A* < 0  |

(see **ExamplesBasics.ipynb** for a discussion of the direction of the contours returned by both scikit-image and opencv in different situations).

*Example*
(Hexagon which rotates anti-clockwise in regular coordinates and clockwise on an imshow plot):
```python
import numpy as np
from imgbasics import contour_properties

l = 1 / np.sqrt(3)
xp = np.array([1, 1, 0, -1, -1, 0])/2
yp = np.array([-l, l, 2*l, l, -l, -2*l])/2

data = contour_properties(xp, yp)
```
should return
```python
data['centroid'] ~ (0, 0)
data['perimeter'] = 6 / sqrt(3) ~ 3.4641,
data['area'] = -sqrt(3)/2 ~ -0.8660
```

## Closest contour (`closest_contour`)

Finds the closest contour (within a list of contours obtained by *scikit-image* or *opencv*) to a certain position (tuple (x, y)). Example with the *example.png* image provided in the package (should select the lowest, bright spot)

```python
from skimage import io, measure
from imgbasics import closest_contour

img = io.imread('example.png')
contours = measure.find_contours(img, 170)

c = closest_contour(contours, (221, 281), edge=True, source='scikit')
```
- If `edge = True`, returns the contour with the edge closest to the position
- If `edge = False` (default), returns the contour with the average position closest to position.
- `source` is the origin of the contours ('scikit' or 'opencv')

*Note:* raises a `ContourError` if no contours in image (`contours` empty).


## Contour coordinates (`contour_coords`)

Following the analysis in the section above (contour `c`), the `contour_coords()` function allow to format the contour into directly usable x, y coordinates for plotting directly on the imshow() image. For example, following the code above:

```python
import matplotlib.pyplot as plt
from imgbasics import contour_coords

x, y = contour_coords(c, source='scikit')

fig, ax = plt.subplots()
ax.imshow(img, cmap='gray')
ax.plot(x, y, -r)
```

## Image transformation module (`imgbasics.transform`)

This module mimicks Scikit Image's `transform` module but with calculations based on OpenCV for order-of-magnitude improvement (typically more than 10-fold) in speed. Right now it only contains the `rotate()` function.

```python
from imgbasics.transform import rotate
from skimage import io

img = io.imread('example.png')
img_rot = rotate(img, angle=-23, resize=True, order=3)  # bicubic interpolation
```



# Interactive cropping demo

With clicks (default):

![](https://raw.githubusercontent.com/ovinc/imgbasics/master/data/imcrop_demo_clicks.gif)

With a draggable rectangle:

![](https://raw.githubusercontent.com/ovinc/imgbasics/master/data/imcrop_demo_draggable.gif)



# Dependencies

- python >= 3.6
- matplotlib
- numpy
- importlib-metadata
- drapo >= 1.2.0
- *[optional]* openCV (cv2), only if using the `imgbasics.transform` module (not listed in the install dependencies of the `imgbasics` package)


# Author

Olivier Vincent

(ovinc.py@gmail.com)

# License

BSD 3-clause (see *LICENSE* file)

BSD 3-Clause License

Copyright (c) 2020, Olivier VINCENT
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* 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.

* 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.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/ovinc/imgbasics",
    "name": "imgbasics",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "image,analysis,crop,imcrop,cropping,contour,contours,centroid,perimeter,area",
    "author": "Olivier Vincent",
    "author_email": "ovinc.py@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/75/0f/fc8d3b6b25559d891be96eef9620e935a6b482f879cf9fce4f4b4abcaeb4/imgbasics-0.3.0.tar.gz",
    "platform": null,
    "description": "About\n=====\n\nBasic image analysis tools, with the following functions:\n\n- `imcrop()`: image cropping, with interactive options,\n- `contour_properties()`: calculate centroid, area, and perimeter of a contour,\n- `closest_contour()`: closest contour to a position,\n- `contour_coords()`: transform contour from scikit-image or opencv into usable x, y data,\n\nThe `imgbasics.transform` module also contains functions mimicking those found in Scikit Image's transform module, but that are based on OpenCV for improved speed. For now it only contains:\n\n- `transform.rotate()`: rotate image\n\n*Note*: the package also defines a `ContourError` class as a custom exception for errors in contour calculations.\n\nInstall\n=======\n\n```bash\npip install imgbasics\n```\n\nQuick start\n===========\n\nBelow is some information to use available functions. Please also consult docstrings and the Jupyter notebooks **ExamplesBasics.ipynb** for more details and examples.\n\n\n## Image cropping (`imcrop`)\n\nImage cropping function; the interactive mode allows the user to define the region of interest on the image interactively, either using clicks or a draggable rectangle.\n\nThe image `img` is assumed to be already loaded in memory as a numpy array (or equivalent, i.e. that supports slicing and defines `shape` and `ndim` attributes)\n\n### Non-interactive mode\n\n```python\nimg_crop = imgbasics.imcrop(img, cropzone)\n```\nCrops the image `img` according to a pre-defined crop rectangle `cropzone = xmin, ymin, width, height`. Contrary to the Matlab imcrop function with the same name, the cropped image is really of the width and height requested in terms of number of pixels, not w+1 and h+1 as in Matlab.\n\n### Interactive mode\n\n```python\nimg_crop, cropzone = imgbasics.imcrop(img)\n```\nCropping rectangle is drawn on the image (img) by either:\n- defining two corners of the rectangle by clicking (default).\n- using a draggable rectangle for selection and pressing \"enter\" (`draggable=True` option)\n\nThe returned cropzone corresponds to `xmin, ymin, width, height`.\n\n*Note*: when selecting, the pixels taken into account are those which have\ntheir centers closest to the click, not their edges closest to the click.\nFor example, to crop to a single pixel, one needs to click two times within\nthis pixel (possibly at the same location). For images with few pixels,\nthis results in a visible offset between the dotted lines plotted after the\nclicks (running through the centers of the pixels clicked) and the final\nrectangle, which runs along the edges of all pixels selected.\n\n### Other arguments\n\nOther arguments are available, e.g. for appearance, visibility, axes, etc. of the cropping tools. See docstrings for details.\n\n\n## Contour properties (`contour_properties`)\n\nReturns centroid position, perimeter and area of a contour as a dictionary with keys `'centroid'` (tuple with x and y position), `'perimeter'` (positive float), `'area'` (signed float). The sign convention for the area *A* differs depending on what type of plot is used (because `plt.imshow()` and `plt.plot()` do not use the same coordinate conventions):\n\n| direction      |  imshow image (`plt.imshow()`)  | regular plot (`plt.plot()`)\n| :---:          | :---:                           | :---:\n| clockwise      |  *A* < 0  |  *A* > 0  |\n| anti-clockwise |  *A* > 0  |  *A* < 0  |\n\n(see **ExamplesBasics.ipynb** for a discussion of the direction of the contours returned by both scikit-image and opencv in different situations).\n\n*Example*\n(Hexagon which rotates anti-clockwise in regular coordinates and clockwise on an imshow plot):\n```python\nimport numpy as np\nfrom imgbasics import contour_properties\n\nl = 1 / np.sqrt(3)\nxp = np.array([1, 1, 0, -1, -1, 0])/2\nyp = np.array([-l, l, 2*l, l, -l, -2*l])/2\n\ndata = contour_properties(xp, yp)\n```\nshould return\n```python\ndata['centroid'] ~ (0, 0)\ndata['perimeter'] = 6 / sqrt(3) ~ 3.4641,\ndata['area'] = -sqrt(3)/2 ~ -0.8660\n```\n\n## Closest contour (`closest_contour`)\n\nFinds the closest contour (within a list of contours obtained by *scikit-image* or *opencv*) to a certain position (tuple (x, y)). Example with the *example.png* image provided in the package (should select the lowest, bright spot)\n\n```python\nfrom skimage import io, measure\nfrom imgbasics import closest_contour\n\nimg = io.imread('example.png')\ncontours = measure.find_contours(img, 170)\n\nc = closest_contour(contours, (221, 281), edge=True, source='scikit')\n```\n- If `edge = True`, returns the contour with the edge closest to the position\n- If `edge = False` (default), returns the contour with the average position closest to position.\n- `source` is the origin of the contours ('scikit' or 'opencv')\n\n*Note:* raises a `ContourError` if no contours in image (`contours` empty).\n\n\n## Contour coordinates (`contour_coords`)\n\nFollowing the analysis in the section above (contour `c`), the `contour_coords()` function allow to format the contour into directly usable x, y coordinates for plotting directly on the imshow() image. For example, following the code above:\n\n```python\nimport matplotlib.pyplot as plt\nfrom imgbasics import contour_coords\n\nx, y = contour_coords(c, source='scikit')\n\nfig, ax = plt.subplots()\nax.imshow(img, cmap='gray')\nax.plot(x, y, -r)\n```\n\n## Image transformation module (`imgbasics.transform`)\n\nThis module mimicks Scikit Image's `transform` module but with calculations based on OpenCV for order-of-magnitude improvement (typically more than 10-fold) in speed. Right now it only contains the `rotate()` function.\n\n```python\nfrom imgbasics.transform import rotate\nfrom skimage import io\n\nimg = io.imread('example.png')\nimg_rot = rotate(img, angle=-23, resize=True, order=3)  # bicubic interpolation\n```\n\n\n\n# Interactive cropping demo\n\nWith clicks (default):\n\n![](https://raw.githubusercontent.com/ovinc/imgbasics/master/data/imcrop_demo_clicks.gif)\n\nWith a draggable rectangle:\n\n![](https://raw.githubusercontent.com/ovinc/imgbasics/master/data/imcrop_demo_draggable.gif)\n\n\n\n# Dependencies\n\n- python >= 3.6\n- matplotlib\n- numpy\n- importlib-metadata\n- drapo >= 1.2.0\n- *[optional]* openCV (cv2), only if using the `imgbasics.transform` module (not listed in the install dependencies of the `imgbasics` package)\n\n\n# Author\n\nOlivier Vincent\n\n(ovinc.py@gmail.com)\n\n# License\n\nBSD 3-clause (see *LICENSE* file)\n\nBSD 3-Clause License\n\nCopyright (c) 2020, Olivier VINCENT\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n",
    "bugtrack_url": null,
    "license": "BSD 3-Clause License",
    "summary": "Basic image analysis tools (cropping, contour properties, etc.)",
    "version": "0.3.0",
    "split_keywords": [
        "image",
        "analysis",
        "crop",
        "imcrop",
        "cropping",
        "contour",
        "contours",
        "centroid",
        "perimeter",
        "area"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0274aa115e5011f0c0644b96e25b9df342d3548909a25353c44f97f7ab3bcfd2",
                "md5": "e943715dfe4ed84286870e270490b701",
                "sha256": "6c4ed69aeacbc5705d85b000a17f1042b143da13d94cb7c80d1881224de6f10d"
            },
            "downloads": -1,
            "filename": "imgbasics-0.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e943715dfe4ed84286870e270490b701",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 13624,
            "upload_time": "2023-01-30T16:36:40",
            "upload_time_iso_8601": "2023-01-30T16:36:40.209762Z",
            "url": "https://files.pythonhosted.org/packages/02/74/aa115e5011f0c0644b96e25b9df342d3548909a25353c44f97f7ab3bcfd2/imgbasics-0.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "750ffc8d3b6b25559d891be96eef9620e935a6b482f879cf9fce4f4b4abcaeb4",
                "md5": "ad52a4bbb42e3e91dfa369a75bf52b70",
                "sha256": "913a36f6f81ccd51010b91ab9eeb96b9a3ef1d540596c033893825a7574834cd"
            },
            "downloads": -1,
            "filename": "imgbasics-0.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "ad52a4bbb42e3e91dfa369a75bf52b70",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 1193138,
            "upload_time": "2023-01-30T16:38:34",
            "upload_time_iso_8601": "2023-01-30T16:38:34.330081Z",
            "url": "https://files.pythonhosted.org/packages/75/0f/fc8d3b6b25559d891be96eef9620e935a6b482f879cf9fce4f4b4abcaeb4/imgbasics-0.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-01-30 16:38:34",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "ovinc",
    "github_project": "imgbasics",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "imgbasics"
}
        
Elapsed time: 0.07327s