473,405 Members | 2,445 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

PIL FITs image decoder

I'm trying to read in a FITs image file for my research, and I decided
that writing a file decoder for the Python imaging library would be the
easiest way to accomplish this for my needs. FITs is a raw data format
used in astronomy.

Anyway, I followed the example in the PIL documentation online, and I
also had a look at the FITs image stub file included with PIL 1.1.5. I
cooked up something that should work (or nearly work), but I keep
running into either one of two errors (below). The crux of the problem
appears to be that my plugin isn't being registered properly and isn't
being read at runtime when I call Image.open().

1.) The library loads the FitsStubImagePlugin.py file from the
site-packages directory (instead of my plugin) and then gives the
following error:

File
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/PIL/ImageFile.py",
line 255, in load
raise IOError("cannot find loader for this %s file" % self.format)
IOError: cannot find loader for this FITS file

2.) I remove the FitsStubImagePlugin.py, pyc files and stick my plugin
in the directory instead (my plugin was already in the PYTHONPATH
before). Then I get the following error:

Traceback (most recent call last):
File "FitsImagePlugin.py", line 111, in ?
image = Image.open(fits_name).save(jpg_name)
File
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/PIL/Image.py",
line 1745, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file

This seems like I'm either doing (or not doing) something really stupid
or the docs are outdated. Any help would be greatly appreciated!

Jeremy

------------------------------ Code below
-----------------------------------

import Image, ImageFile

_handler = None

##
# Install application-specific FITS image handler.
#
# @param handler Handler object.

def register_handler(handler):
global _handler
_handler = handler

# --------------------------------------------------------------------
# Image adapter

def _accept(prefix):
return prefix[:6] == "SIMPLE"

class FitsImageFile(ImageFile.StubImageFile):
#class FitsImageFile(ImageFile.ImageFile):

format = "FITS"
format_description = "FITs raw image"

def _open(self):

# byte offset for FITs images
byte_offset = 2880

# check header for valid FITs image
header_data = self.fp.read(byte_offset)

# headers are stored in 80 character strings, so sort them out
into a
# nice list
i = 0
headers = []
while header_data[i] != "\n" and i < len(header_data):
headers.append(header_data[i:i + 80])
i += 81

# parse individual headers
ok = False
for header in headers:
words = header.split()

try:
keyword = words[0]
value = words[2]
except IndexError:
ok = False
break

if keyword == "NAXIS" and value == 2:
ok = True
elif keyword == "NAXIS1":
xsize = value
elif keyword == "NAXIS2":
ysize = value

if not ok:
raise ValueError("file is not a valid FITs image")

# size in pixels (width, height)
self.size = (xsize, ysize)

# mode setting is always greyscale
self.mode = "F"

# data descriptor
self.tile = [("raw", (0, 0) + self.size, byte_offset, ("F", 0,
-1))]

# is this needed?
loader = self._load()
if loader:
loader.open(self)

def _load(self):
return _handler

def _save(im, fp, filename):
if _handler is None or not hasattr("_handler", "save"):
raise IOError("FITS save handler not installed")
_handler.save(im, fp, filename)

# register the plugin
Image.register_open(FitsImageFile.format, FitsImageFile, _accept)
Image.register_save(FitsImageFile.format, _save)

# method given in docs
#Image.register_open(FitsImageFile.format, FitsImageFile)

Image.register_extension(FitsImageFile.format, ".fits")
Image.register_extension(FitsImageFile.format, ".fit")

# test code
if __name__ == "__main__":
import os

fits_name = "fpC-001739-r1-0304.fit"
jpg_name = os.path.splitext(fits_name)[0] + ".jpg"

image = Image.open(fits_name).save(jpg_name)
print "Converted FITs image '%s' to jpeg image '%s'" % (fits_name,
jpg_name)

Nov 22 '05 #1
8 5567
"jbrewer" wrote:
I'm trying to read in a FITs image file for my research, and I decided
that writing a file decoder for the Python imaging library would be the
easiest way to accomplish this for my needs. FITs is a raw data format
used in astronomy.

Anyway, I followed the example in the PIL documentation online, and I
also had a look at the FITs image stub file included with PIL 1.1.5. I
cooked up something that should work (or nearly work), but I keep
running into either one of two errors (below). The crux of the problem
appears to be that my plugin isn't being registered properly and isn't
being read at runtime when I call Image.open().

1.) The library loads the FitsStubImagePlugin.py file from the
site-packages directory (instead of my plugin) and then gives the
following error:


unfortunately, the stub loaders (which were introduced in 1.1.5) may over-
ride more specific plugins. this will be fixed in 1.1.6.

I don't see any obvious problems with your file, except that you should in-
herit from ImageFile, not StubImageFile:

class FitsImageFile(ImageFile.StubImageFile):

should be

class FitsImageFile(ImageFile.ImageFile):

but I assume you've already tried that.

if you can you mail me (or point me to) a sample file, I can take a look.

</F>

Nov 22 '05 #2
jbrewer wrote:
I'm trying to read in a FITs image file for my research, and I decided
that writing a file decoder for the Python imaging library would be the
easiest way to accomplish this for my needs. FITs is a raw data format
used in astronomy.


http://www.stsci.edu/resources/software_hardware/pyfits

--
Robert Kern
ro*********@gmail.com

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Nov 22 '05 #3
>http://www.stsci.edu/resources/software_hardware/pyfits

I know and love PyFits, but I need to be able to do draw shapes on a
FITs image (and perhaps some other operations), and I don't believe
that PyFits allows these kinds of operations. It might be possible to
import the data into a numarray object and turn that into something PIL
can read, though.

Jeremy

Nov 22 '05 #4
jbrewer wrote:
http://www.stsci.edu/resources/software_hardware/pyfits


I know and love PyFits, but I need to be able to do draw shapes on a
FITs image (and perhaps some other operations), and I don't believe
that PyFits allows these kinds of operations. It might be possible to
import the data into a numarray object and turn that into something PIL
can read, though.


If you can bear having two copies in memory, Image.frombuffer()
generally does the trick.

--
Robert Kern
ro*********@gmail.com

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Nov 22 '05 #5
>If you can bear having two copies in memory, Image.frombuffer()
generally does the trick.


What arguments do you pass to this function, and do you flatten the
array from the FITs image? I this but got garbage out for the image.

Jeremy

Nov 22 '05 #6
>If you can bear having two copies in memory, Image.frombuffer()
generally does the trick.


Also, does PIL have a contrast / scale option that is similar to zscale
in ds9 or equalize in Image Magick?

Jeremy

Nov 22 '05 #7
jbrewer wrote:

[I wrote:]
If you can bear having two copies in memory, Image.frombuffer()
generally does the trick.


What arguments do you pass to this function, and do you flatten the
array from the FITs image? I this but got garbage out for the image.


The array would have to be contiguous, which it may not be immediately
coming out of PyFITS. You also need to be sure that you are using the
right mode for the data.

In [7]: import Image

In [8]: import numarray

In [9]: z = numarray.zeros((256,256)).astype(numarray.UInt8)

In [10]: z[128,:] = 255

In [11]: img = Image.frombuffer('L', (256,256), z)

That creates a black image with a white, horizontal line in the middle.

--
Robert Kern
ro*********@gmail.com

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Nov 22 '05 #8
I tried following your simple example (I already had something similar)
but with no luck. I'm completely stumped as to why this doesn't work.
I even tried manually scaling the data to be in the range 0-255 out of
desperation. The data is definitely contiguous and 32 bit floating
point. At this point I've tried everything I can think of. Any ideas?

Jeremy

# open the fits file using pyfits
fits = pyfits.open(fitsfile)
xsize, ysize = fits[0].data.shape
data = fits[0].data.astype("Float32")
fits.close()

# now create an image object
image = Image.frombuffer("F", (xsize, ysize), data)

# scale the data be 256 bit unsigned integers
#int_data = numarray.zeros((xsize, ysize)).astype("UInt8")
#min = data.min()
#max = data.max()
#for i in arange(xsize):
# for j in arange(ysize):
# scaled_value = (data[i, j] - min) * (255.0 / (max - min))
# int_data[i, j] = int(scaled_value + 0.5)

#image = Image.frombuffer("L", (xsize, ysize), int_data)

Nov 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Premshree Pillai | last post by:
Hello, Is there a Py module available using which I can find the width and height of any image format? -Premshree ===== -Premshree http://www.qiksearch.com/]
17
by: PyPK | last post by:
Hi I am looking for a simple tiff Image reader/writer in python.Can anyone point me to the right one.
0
by: S Etchelecu | last post by:
I'm having trouble understanding the MIME::Decoder usage. Within the context of a MIME email handling program I have an array, @data, and I want to uuencode it. I thought I could instantiate a...
8
by: Dave Quigley | last post by:
Hello everyone.... Im currently starting my targa support project again for ..NET and I am wondering if there are any particular interfaces or classes that Im supposed to extend in order to do this...
6
by: nichughes | last post by:
Hello all, A question relating to http://www.entrust-systems.net/ Just for a change I have run into a problem that seems to be OS specific rather than browser specific - the box image that is...
2
by: bharathv6 | last post by:
i need to do is modify the image in memory like resizing the image in memory etc ... with out saving it disk as i have to return back the image with out saving it disk PIL supports the use of...
1
by: bharathv6 | last post by:
i need to do is modify the image in memory like resizing the image in memory etc ... with out saving it disk as i have to return back the image with out saving it disk PIL supports the use of...
0
by: Victory | last post by:
Hi, I have looked through the MSDN but looks like there is nothing there that tells me how to use a Decoder object and actually get information about a JPG image. I need to check the frame header...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.