473,651 Members | 2,533 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

jpeg image read class

hi
i am new to python and PIL and was trying to write a class to read and
write RGB color model jpeg images..
i came up with this class below..i want to know if this is the way to
read/write the RGB color model jpeg..if anyone can give feedback (esp
on the methods writeImage1( ) and writeImage2( ) it wd help my
studies ..
TIA
dn

#jpgpy.py

import Image
from sys import argv
from numpy import array
class JPGFile:
def __init__(self,f ilename):
self._filename= filename
self._height=0
self._width=0
self._mode=""
self._rgblist=[]
self._pixellist =[]
self._pixarray= None
self.readImage( )

def getheight(self) :
return self._height
def getwidth(self):
return self._width

def getpixellist(se lf):
return self._pixellist

def getrgblist(self ):
return self._rgblist

def makepixval(self ,(r,g,b)):
alpha=255
pixval=(alpha<< 24)|(r<<16 )|( g<<8) | b
return pixval

def readImage(self) :
im=Image.open(s elf._filename)
self._mode=im.m ode
self._width,sel f._height=im.si ze
for y in range(self._hei ght):
for x in range(self._wid th):
r,g,b=im.getpix el((x,y))
self._rgblist.a ppend((r,g,b))
pval=self.makep ixval((r,g,b))
self._pixellist .append(pval)
self._pixarray= array(self._pix ellist,float)

def makergb(self,pi xval):
alpha=pixval>>2 4
red=(pixval>>16 )&255
green=(pixval>> 8 )&255
blue=(pixval)& 255
return red,green,blue

def writeImage1(sel f,fname,data,wi dth,height):
imnew=Image.new (self._mode,(wi dth,height))
newrgblist=[]
for i in range(len(data) ):
r,g,b=self.make rgb(data[i])
newrgblist.appe nd((r,g,b))
index=0
for y in range(height):
for x in range(width):
imnew.putpixel( (x,y),newrgblis t[index])
index+=1
imnew.save(fnam e)

def writeImage2(sel f,fname,data,wi dth,height):
imnew=Image.new (self._mode,(wi dth,height))
newrgblist=[]
for i in range(len(data) ):
r,g,b=self.make rgb(data[i])
newrgblist.appe nd((r,g,b))
imnew.putdata(n ewrgblist)
imnew.save(fnam e)
imgname=argv[1] #Usage: python jpgpy.py myimage.jpg
print "to read from:",imgname
x=JPGFile(imgna me)
print x.getheight()," ",x.getwidt h()
pixlist=x.getpi xellist()
rgbtpllist=x.ge trgblist()
w=x.getwidth()
h=x.getheight()
x.writeImage1(" newimage1.jpg", pixlist,w,h)

Oct 31 '07 #1
2 2249
On Wed, 31 Oct 2007 06:48:18 +0000, de****@gmail.co m wrote:
i am new to python and PIL and was trying to write a class to read and
write RGB color model jpeg images..
PIL already offers such a class.
i came up with this class below..i want to know if this is the way to
read/write the RGB color model jpeg..if anyone can give feedback (esp
on the methods writeImage1( ) and writeImage2( ) it wd help my
studies ..
Those are bad names. What does 1 and 2 mean in them!?
class JPGFile:
def __init__(self,f ilename):
self._filename= filename
self._height=0
self._width=0
self._mode=""
This will always be 'RGB' so why store it?
self._rgblist=[]
self._pixellist =[]
self._pixarray= None
In the end you store the image *three times* in different representations .
Is that really necessary?
self.readImage( )
Is `readImage()` supposed to be called again later? If not you might add
an underscore in front and give the file name as argument. Then you could
drop `self._filename `.
def getheight(self) :
return self._height
def getwidth(self):
return self._width

def getpixellist(se lf):
return self._pixellist

def getrgblist(self ):
return self._rgblist
Maybe get rid of those trivial getters and the underscore in front of the
names. That's a little "unpythonic ". Do a web search for "Python is not
Java".
def makepixval(self ,(r,g,b)):
alpha=255
pixval=(alpha<< 24)|(r<<16 )|( g<<8) | b
return pixval
Looks like an ordinary function to me. `self` is not used.
def readImage(self) :
im=Image.open(s elf._filename)
self._mode=im.m ode
self._width,sel f._height=im.si ze
for y in range(self._hei ght):
for x in range(self._wid th):
r,g,b=im.getpix el((x,y))
self._rgblist.a ppend((r,g,b))
pval=self.makep ixval((r,g,b))
self._pixellist .append(pval)
self._pixarray= array(self._pix ellist,float)
Iterating over `im.getdata()` should be simpler and faster than the nested
loops.
def makergb(self,pi xval):
alpha=pixval>>2 4
red=(pixval>>16 )&255
green=(pixval>> 8 )&255
blue=(pixval)& 255
return red,green,blue
Again a simple function.
def writeImage1(sel f,fname,data,wi dth,height):
imnew=Image.new (self._mode,(wi dth,height))
newrgblist=[]
for i in range(len(data) ):
r,g,b=self.make rgb(data[i])
newrgblist.appe nd((r,g,b))
If you have ``for i in range(len(somet hing)):`` you almost always really
wanted to iterate over `something` directly. That loop can be written as:

for pixval in data:
rgb = pixval2rgb(pixv al)
rgbs.append(rgb )

Or even shorter in one line:

rgbs = map(pixval2rgb, data)

If the `numpy` array is what you want/need it might be more efficient to do
the RGB to "pixval" conversion with `numpy`. It should be faster to shift
and "or" a whole array instead of every pixel one by one in pure Python.

Ciao,
Marc 'BlackJack' Rintsch
Oct 31 '07 #2
Marc
thanx for the reply..it wd help me to write better code..i was trying
to learn PIL and python and may be my java background made it
unpythonic..wil l try to improve it
again many thanx
dn

Nov 1 '07 #3

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

Similar topics

2
1911
by: Suzanne | last post by:
Hi all, I'm attempting to save images (that are in jpeg format) to a database column of type image. I've read over the Microsoft Knowledge Base articles for this and I can get things working when the image is in a gif format - but not when the image is in a jpeg format - I get the error that the file can not be found (& I've checked - the file is there)! My code is :
3
2464
by: bull.enteract | last post by:
Ok, I start off with a bitmap image. I encode it as a jpeg and send it across the network and pick it up on the other end. Now I have the jpeg image on the other end as an arrray of bytes and I want to display it in a picturebox control. How the heck do I convert this byte into a bitmap? Here is the pertinent code I use to convert it to a jpeg on the server and send it to client.. ....Bitmap workerBmp = new Bitmap(bmp);
16
11851
by: David Lauberts | last post by:
Hi Wonder if someone has some words of wisdom. I have a access 2002 form that contains 2 graph objects that overlay each other and would like to export them as a JPEG to use in a presentation. I can do this individually for each graph but this does not help me as I need both on the same JPEG. I thought I would try an export the form that contains both but I am having trouble. (My VBA is self taught and a little knowledge is...
3
3398
by: 246C57AE-40DD-4d6b-9E8D-B0F5757BB2A8 | last post by:
Hi. Why can't I read TIFFs compressed by JPEG using GDI+ Image class? I always get out of memory exception. Thanx.
5
4728
by: TheGanjaMan | last post by:
Hi everyone, I'm trying to write up a simple image stamper application that stamps the Exif date information from the jpegs that I've taken from my digital camera and saves the new file with the date stamped on the lower right part of the picture. (I'm not an advanced programmer so my code may not be 100% efficient - sorry, I'm still learning) Everything works fine until the saving part. I've been able to read the file into a...
1
7822
by: Smokey Grindel | last post by:
I have a bitmap object I want to return as a JPEG image with a compression set at 90% and progressive passes enabled, how can I do this in .NET 2.0? Progressive passes are not necessary but the compression ratio is.. thanks!
4
3810
by: Greg | last post by:
I've searched everywhere for a solution Microsoft .NET Framework V 2.0.50727 AutoEventWireup="false" image2.aspx resize an image on the fly but Page_Load is triggered twice: Any suggestion? Here is the code behind:
4
3060
by: Pacino | last post by:
Hi, everyone, I am wondering whether it's possible to read part (e.g. 1000*1000) of a huge jpeg file (e.g. 30000*30000) and save it to another jpeg file by pure python. I failed to read the whole file and split it, because it would cost 2GB memory. Can anyone help me? Any comments would be appreciated. Thanks.
2
4970
by: mndprasad | last post by:
hi all i am doing a project in java where i need to convert 10 jpeg images into a single tiff image..conversion of single jpeg image to single tiff is happening but embedding all the 10 jpeg images into a single tiff is not happening..i hav tried out with single image conversion.. My code is *********************** import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO;
0
8795
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8460
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
8576
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7296
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
5609
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
4143
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
4281
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1906
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1585
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.