EzDevInfo.com

mahotas

Computer Vision in Python Mahotas: Computer Vision in Python — mahotas 1.4.0+git documentation

Python module Mahotas thresholding issue

I'm using this tutorial http://pythonvision.org/basic-tutorial

However when I pass a png image:

T = mahotas.thresholding.otsu(dna)

I get an error:

TypeError: mahotas.otsu: This function only accepts integer types (passed array of type float32)

Does anyone have exp. w/this issue? Thanks!


Source: (StackOverflow)

Reading and writing images with Mahotas

I'm trying to write an image with Mahotas and finding it strangely difficult.

img = mahotas.imread('foo.png', True)
mahotas.imsave('bar.png', img)

the error I'm gettings is:

ValueError: mahotas.freeimage: cannot write arrays of given type and shape.

I'm on OS X and used brew to install freeimage.


Source: (StackOverflow)

Advertisements

Unable to locate freeimage after install of mahotas in Python

Hi I am new to Python and am following the Python Image Tutorial.

The following executes with no errors after installing the packages described in the tutorial

import numpy
import scipy
import pylab
import pymorph
import mahotas
from scipy import ndimage

However when I try reading an image

image = mahotas.imread('picture_file.jpg')

I get

image = mahotas.imread('image_file.jpg') Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.6/dist-packages/mahotas-0.6.4-py2.6-linux-i686.egg/mahotas/init.py", line 68, in imread raise ImportError('mahotas.imread dependends on freeimage. Could not find it. Error was: %s' % e) ImportError: mahotas.imread dependends on freeimage. Could not find it. Error was: mahotas.freeimage: could not find libFreeImage in any of the following directories: '/usr/local/lib/python2.6/dist-packages/mahotas-0.6.4-py2.6-linux-i686.egg/mahotas', '/lib', '/usr/lib', '/usr/local/lib', '/opt/local/lib'

I tried installing FreeImagePy and can import it with no problems but it does not help. I have tried adding to the Python path using package sys but not help either.

EDIT: I should have mentioned that all the packages except pymorph and mahotas was installed on my linux box doing '*sudo apt-get install package_name*' while pymorph and mahotas was installed by downloading and doing 'sudo python setup.py install'.


Source: (StackOverflow)

How can i know if there are white pixels in a binary image in some coordinates (stored in a list) in python?

I have a numpy array binary (black and white) image and coordinates in a list of tuples like:

coordlist =[(110, 110), (110, 111), (110, 112), (110, 113), (110, 114), (110, 115), (110, 116), (110, 117), (110, 118), (110, 119), (110, 120), (100, 110), (101, 111), (102, 112), (103, 113), (104, 114), (105, 115), (106, 116), (107, 117), (108, 118), (109, 119), (110, 120)]

or as:

coordx = [110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]
coordy = [110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120]

How can i check if there is a "white" pixel in the image with that coordinates list? I also would like check the white pixels that are around 3 pixels range far from that coordinates list.

i.e.:

for i, j in coordx, coordy:
    for k in a range (k-3, k + 3)
        for l in a range (l-3, l + 3)
            #checking white pixels also for pixel near coordinates list

I thought about "where" function.

from skimage import morphology
import numpy as np

path = 'image/a.jpg'
col = mh.imread(path)
bn0 = col[:,:,0]
bn = (bn0 < 127)
bnsk = morphology.skeletonize(bn)
bnskInt = np.array(bnsk, dtype=np.uint8)

#finding if there are white pixel in the coord list and around that in a 5 pixel range
for i in coordlist:
np.where(?)

UPDATE.

I tried to use shape (128, 128) instead of (128, 128, 3) because my image have this shape: (a,b) but now it does not find the white pixels! Why in this way does it find anything?

    white_pixel = np.array([255, 255])
    img = np.random.randint(0, 256, (128, 128))
    print(img[150])
    print(img.shape)
    img[110, 110] = 255
    img[109, 110] = 255

    mask = np.zeros((128, 128), dtype=bool)
    mask[coordx, coordy] = 1
    #structure = np.ones((3, 3, 1))
    #mask = scipy.ndimage.morphology.binary_dilation(mask, structure)

    is_white = np.all((img * mask) == white_pixel, axis=-1)

    # This will tell you which pixels are white
    print np.where(is_white)

    # This will tell you if any pixels are white
    print np.any(is_white)

output:

(array([], dtype=int32),)
False

Source: (StackOverflow)

error while installing mahotas to python 2.7

I am using command prompt for installing Manhotas 1.1.0. I have mahotas in zip file and I have extracted it out. My procedure was:' python setup.py install' . But,its giving me error:

enter image description here

Thanks in advance!


Source: (StackOverflow)

python mahotas.imread reads a 2d image as 3d

I have an image saved by another code of mine. The image is a normal JPG file. I saved it with imsave.

now when I'm reading it in another code, it seems to be 3d :S

the image is here.

and a simple code to read it is this :

import mahotas

img = mahotas.imread('d:/normal.jpg')
print img.shape, img.dtype

Source: (StackOverflow)

Image Conversion between cv2, cv, mahotas, and SimpleCV

I am having to do a lot of vision related work in Python lately, and I am facing a lot of difficulties switching between formats. When I read an image using Mahotas, I cannot seem to get it to cv2, though they are both using numpy.ndarray. SimpleCV can take OpenCV images easily, but getting SimpleCV image out for legacy cv or mahotas seems to be quite a task.

Some format conversion syntaxes would be really appreciated. For example, if I open a greyscale image using mahotas, it is treated to be in floating point colour space by default, as I gather. Even when I assign the type as numpy.uint8, cv2 cannot seem to recognise it as an array. I do not know how to solve this problem. I am not having much luck with colour images either. I am using Python 2.7 32bit on Ubuntu Oneiric Ocelot.

Thanks in advance!


Source: (StackOverflow)

enthought mahotas.imread cannot find freeimage

I'm new to python and it was recommended that I use Canopy. I'm trying to follow along with this tutorial, but I get stuck at the mahotas.imread line. I get an error saying that ends with this:

Full error was: mahotas.freeimage: could not find libFreeImage in any of the following directories: '/Users/RJD/Library/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/mahotas', '/lib', '/usr/lib', '/usr/local/lib', '/opt/local/lib'

I've added the mahotas package via the package manager to no avail. Also tried the steps here, with no different result.

I am actually able to find 'freeimage.py' and 'freeimage.pyc' in '/Users/RJD/Library/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/mahotas'. How do I go about telling Canopy that it is there?!

Any help would be very much appreciated.

Cheers, R


Source: (StackOverflow)

microscopy image segmentation: bacteria segmentation with python

I am trying to segment some microscopy bright-field images showing some E. coli bacteria. The picture I am working with resembles this one (even if this one is obtained with phase contrast):

microscopy bright-field image

my problem is that after running my segmentation function (OtsuMask below) I cannot distinguish dividing bacteria (you can try my code below on the sample image). This means that I get one single labeled region for a couple of bacteria which are joined by their end, instead of two different labeled images. The boundary between two dividing bacteria is too narrow to be highlighted by the morphological operations I perform on the thresholded image, but I guess there must be a way to achieve my goal.

Any ideas/suggestions?

import scipy as sp
import numpy as np
from scipy import optimize
import mahotas as mht
from scipy import ndimage
import pylab as plt


def OtsuMask(img,dilation_size=2,erosion_size=1,remove_size=500):

    img_thres=np.asarray(img)
    s=np.shape(img)    
    p0=np.array([0,0,0])

    p0[0]=(img[0,0]-img[0,-1])/512.    
    p0[1]=(img[1,0]-img[1,-1])/512.
    p0[2]=img.mean()

    [x,y]=np.meshgrid(np.arange(s[1]),np.arange(s[0]))

    p=fitplane(img,p0)    
    img=img-myplane(p,x,y)    


    m=img.min()
    img=img-m
    img=abs(img)
    img=img.astype(uint16)

    """perform thresholding with Otsu"""
    T = mht.thresholding.otsu(img,2)
    print T
    img_thres=img
    img_thres[img<T*0.9]=0
    img_thres[img>T*0.9]=1


    img_thres=-img_thres+1  

    """morphological operations"""
    diskD=createDisk(dilation_size)
    diskE=createDisk(erosion_size)

    img_thres=ndimage.morphology.binary_dilation(img_thres,diskD)   

    labeled_im,N=mht.label(img_thres)
    label_sizes=mht.labeled.labeled_size(labeled_im)
    labeled_im=mht.labeled.remove_regions(labeled_im,np.where(label_sizes<remove_size))    


    figure();
    imshow(labeled_im)

    return labeled_im

def myplane(p,x,y):

    return p[0]*x+p[1]*y+p[2] 

def res(p,data,x,y):

    a=(data-myplane(p,x,y));

    return array(np.sum(np.abs(a**2)))

def fitplane(data,p0):

    s=shape(data);

    [x,y]=meshgrid(arange(s[1]),arange(s[0]));
    print shape(x), shape(y)

    p=optimize.fmin(res,p0,args=(data,x,y));
    print p
    return p


def createDisk( size ):
    x, y = np.meshgrid( np.arange( -size, size ), np.arange( -size, size ) )
    diskMask = ( ( x + .5 )**2 + ( y + .5 )**2 < size**2)
    return diskMask

THE FIRST PART OF THE CODE IN OtsuMask CONSIST OF A PLANE FITTING AND SUBTRACTION.


Source: (StackOverflow)

How can I apply a function to an image proportionally to his size in python?

I have an image and I would like to apply dilation, erosion, closing, opening operations proportionally to the image size.

In my code I divided the images in three sets but I think it's better to use other better ways. How can I change gradually the disk size for my operations?

import pymorph as pm
import mahtoas as mh 
if (shape[0] < 100):
    w =  (shape[0]/100 )*0.2
elif(shape[0]> 100 and shape[0] <220):
    w =  (shape[0]/100 )*1.0
else:
    w = (shape[0]/100)*3

#structuring elements
disk7 = pm.sedisk(w)
bfork = mh.morph.dilate(bfork, disk7)

Source: (StackOverflow)

Cannot determine type of file

Hi i have just started learning image processing using python. When i tried to open an image that i downloaded from the net, I keep getting this error and I have no idea about how to resolve it. Can anyone please help me with this?

>>> dna=mahotas.imread('dna.jpeg')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\mahotas\io\freeimage.py", line 773, in imread
    img = read(filename)
  File "C:\Python27\lib\site-packages\mahotas\io\freeimage.py", line 444, in read
    bitmap = _read_bitmap(filename, flags)
  File "C:\Python27\lib\site-packages\mahotas\io\freeimage.py", line 490, in _read_bitmap
    'mahotas.freeimage: cannot determine type of file %s' % filename)
ValueError: mahotas.freeimage: cannot determine type of file dna.jpeg

Source: (StackOverflow)

Image manipulation in Python (compute graph edge distance between nodes (region centroids)

I need to binarize image and compute selected microvessels (black-brown ), then to split image array into 100 equal parts and set centroids in these image regions (with max and min numbers of black pixels) and compute graph edge distance between the nodes lying in these centers. Does anybody has experience and know what functions to use in Python?

Here is the starting code:

 import numpy as np
 import scipy
 import pylab
 #import pymorph
 import mahotas
 from scipy import ndimage

 img = mahotas.imread('imagetest.tif')


 T = mahotas.thresholding.otsu(img)
 pylab.imshow(img > T)
 pylab.show()

Thank you much


Source: (StackOverflow)

Detect objects on a white background in Python

I'm trying to use Python to detect how many objects are on a white surface. An example image is found at the end of this post.

I'm wondering how I should do this, mainly because the background is white and most of the time it gets detected as foreground.

What I have now in Python based on this tutorial (http://pythonvision.org/basic-tutorial) uses several libraries and detects the white as the object so count is 1, the tools get detected as background and thus are ignored:

dna = mahotas.imread('dna.jpeg')
dna = dna.squeeze()
dna = pymorph.to_gray(dna)


print dna.shape
print dna.dtype
print dna.max()
print dna.min()

dnaf = ndimage.gaussian_filter(dna, 8)
T = mahotas.thresholding.otsu(dnaf)
labeled, nr_objects = ndimage.label(dnaf > T)
print nr_objects
pylab.imshow(labeled)
pylab.jet()
pylab.show()

Are there any options for getting the white part as background and the tools as foreground?

Thanks in advance!

Example image: enter image description here

The segmented image where red is foreground and blue background (the few tools merging is not a problem):

enter image description here


Source: (StackOverflow)

Why after histogram equalization (scikit image) and Otsu mahotas method in some images get out big white squares?

I used histogram equalization and adaptation for erase illumination from the grayscale images:

import scipy
import numpy as np
import pymorph as pm
import mahotas as mh
from skimage import morphology
from skimage import io
from matplotlib import pyplot as plt
from skimage import data, img_as_float
from skimage import exposure

mhgray = io.imread(path)
mhgray = mhgray[:,:,0]

#thresh = mh.otsu(binimg)
#gray =( binimg< thresh)
img = color.rgb2gray(mhgray)   
#img = mhgray #binimg

#from skimage import exposure
#print dir(exposure)

# Contrast stretching
p2 = np.percentile(img, 2)
p98 = np.percentile(img, 98)
#img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98))
img_rescale = exposure.rescale_intensity(img, out_range=(0, 255))

# Equalization
img_eq = exposure.equalize_hist(img)

# Adaptive Equalization
img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.03)

but after the histogram equalization, i use otsu method:

thresh = mh.otsu(binimg) 
gray =( binimg< thresh)

the thresh value for the next example is: 16329

Source image:

enter image description here

After histogram equalization and adaptation:

source image

After Otsu method:

Image after Otsu

The image before Otsu is an array of uint16, after Otsu is a numpy array of bool.

In stackoverflow suggested me to use histogram equalization to avoid illumination problems.

It is for the grey background? How can i fix it?


Source: (StackOverflow)

How to write a big amount of multipage TIFF files?

Hi everybody from a beginner in Python. I try to convert a huge file of raw video data into multiple multipage TIFF files by using the "freeimage.write_multipage()" function of the freeimage package from the Mahotas library (Python 2.7). Unfortunately, it seems that this "very easy to use" function doesn't release memory when running the script. So, my script works fine for small input raw files (less than 1 GB) but crashes with bigger files (a 3 GB input file crashes with Win XP pro 32 - ram 3.2 GB). My goal is to convert input files up to 1.5 TB.

When running my script, the Windows Task manager shows an increase of the used ram, output file after output file until the crash which release all the used ram. An extract of the reported error is: "... RuntimeError : mahotas.freeimage: FreeImage error: Memory allocation failed..."

From Stackoverflow, I saw different advices for building multipages TIFF files with using scripts in Image Magic or Irfanview but I think it's impossible for my needs (I have thousands of pictures to assemble). Thank you for any help.


Source: (StackOverflow)