473,770 Members | 1,891 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 FitsStubImagePl ugin.py file from the
site-packages directory (instead of my plugin) and then gives the
following error:

File
"/System/Library/Frameworks/Python.framewor k/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 FitsStubImagePl ugin.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 "FitsImagePlugi n.py", line 111, in ?
image = Image.open(fits _name).save(jpg _name)
File
"/System/Library/Frameworks/Python.framewor k/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_handle r(handler):
global _handler
_handler = handler

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

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

class FitsImageFile(I mageFile.StubIm ageFile):
#class FitsImageFile(I mageFile.ImageF ile):

format = "FITS"
format_descript ion = "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(by te_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("fil e 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(sel f)

def _load(self):
return _handler

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

# register the plugin
Image.register_ open(FitsImageF ile.format, FitsImageFile, _accept)
Image.register_ save(FitsImageF ile.format, _save)

# method given in docs
#Image.register _open(FitsImage File.format, FitsImageFile)

Image.register_ extension(FitsI mageFile.format , ".fits")
Image.register_ extension(FitsI mageFile.format , ".fit")

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

fits_name = "fpC-001739-r1-0304.fit"
jpg_name = os.path.splitex t(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 5607
"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 FitsStubImagePl ugin.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(I mageFile.StubIm ageFile):

should be

class FitsImageFile(I mageFile.ImageF ile):

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*********@gma il.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.frombuffe r()
generally does the trick.

--
Robert Kern
ro*********@gma il.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.frombuffe r()
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.frombuffe r()
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.frombuffe r()
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)).asty pe(numarray.UIn t8)

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

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

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

--
Robert Kern
ro*********@gma il.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(fit sfile)
xsize, ysize = fits[0].data.shape
data = fits[0].data.astype("F loat32")
fits.close()

# now create an image object
image = Image.frombuffe r("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_valu e + 0.5)

#image = Image.frombuffe r("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
4054
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
10041
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
3345
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 MIME::Decoder with an encoding of 'x-uuencode' and then call the encode method as, my $decoder = new MIME::Decoder('x-uuencode'); $decoder->encode(@data, @uudata); However, the encode method only accepts STREAMs as arguments. Obviously I
8
2035
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 in a propper manner. I could try to replicate Bitmap however I believe the problem I ran into was that the base classes for images are sealed in .net so I cant inherit from them... Any suggestions would be greatly apprectiated. I may consider...
6
1991
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 acting as a faux border for the main text block shows nasty image effects on the outside when using either Firefox or Konqueror on Suse Linux. This image is set to resize with the browser window (and hence the text) and this seems to be what...
2
3233
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 StringIO objects being passed in place of file objects. StringIO objects are binary strings of variable length that are kept in memory so i saved the image in stringio objects the following code does that file = StringIO() image.save(file, "JPEG") ...
1
11089
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 StringIO objects being passed in place of file objects. StringIO objects are binary strings of variable length that are kept in memory so i saved the image in stringio objects the following code does that for gif image ...
0
1236
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 and see what type of DCT the image is made with like DCT with Huffman coding or Extended sequential DCT with arithmetic coding. Any help is appreciated, Mars *** Sent via Developersdex http://www.developersdex.com ***
0
9617
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9453
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10099
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10036
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8929
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.