Package: imgbasics
AboutBasic 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,Theimgbasics.transformmodule 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 imageNote: the package also defines aContourErrorclass as a custom exception for errors in contour calculations.InstallpipinstallimgbasicsQuick startBelow is some information to use available functions. Please also consult docstrings and the Jupyter notebooksExamplesBasics.ipynbfor 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 imageimgis assumed to be already loaded in memory as a numpy array (or equivalent, i.e. that supports slicing and definesshapeandndimattributes)Non-interactive modeimg_crop=imgbasics.imcrop(img,cropzone)Crops the imageimgaccording to a pre-defined crop rectanglecropzone = 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 modeimg_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=Trueoption)The returned cropzone corresponds toxmin, 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 argumentsOther 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 areaAdiffers depending on what type of plot is used (becauseplt.imshow()andplt.plot()do not use the same coordinate conventions):directionimshow image (plt.imshow())regular plot (plt.plot())clockwiseA< 0A> 0anti-clockwiseA> 0A< 0(seeExamplesBasics.ipynbfor 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):importnumpyasnpfromimgbasicsimportcontour_propertiesl=1/np.sqrt(3)xp=np.array([1,1,0,-1,-1,0])/2yp=np.array([-l,l,2*l,l,-l,-2*l])/2data=contour_properties(xp,yp)should returndata['centroid']~(0,0)data['perimeter']=6/sqrt(3)~3.4641,data['area']=-sqrt(3)/2~-0.8660Closest contour (closest_contour)Finds the closest contour (within a list of contours obtained byscikit-imageoropencv) to a certain position (tuple (x, y)). Example with theexample.pngimage provided in the package (should select the lowest, bright spot)fromskimageimportio,measurefromimgbasicsimportclosest_contourimg=io.imread('example.png')contours=measure.find_contours(img,170)c=closest_contour(contours,(221,281),edge=True,source='scikit')Ifedge = True, returns the contour with the edge closest to the positionIfedge = False(default), returns the contour with the average position closest to position.sourceis the origin of the contours ('scikit' or 'opencv')Note:raises aContourErrorif no contours in image (contoursempty).Contour coordinates (contour_coords)Following the analysis in the section above (contourc), thecontour_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:importmatplotlib.pyplotaspltfromimgbasicsimportcontour_coordsx,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'stransformmodule but with calculations based on OpenCV for order-of-magnitude improvement (typically more than 10-fold) in speed. Right now it only contains therotate()function.fromimgbasics.transformimportrotatefromskimageimportioimg=io.imread('example.png')img_rot=rotate(img,angle=-23,resize=True,order=3)# bicubic interpolationInteractive cropping demoWith clicks (default):With a draggable rectangle:Dependenciespython >= 3.6matplotlibnumpyimportlib-metadatadrapo >= 1.2.0[optional]openCV (cv2), only if using theimgbasics.transformmodule (not listed in the install dependencies of theimgbasicspackage)AuthorOlivier Vincent(ovinc.py@gmail.com)LicenseBSD 3-clause (seeLICENSEfile)BSD 3-Clause LicenseCopyright (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.