Error .. Please Help

Dave Angel d at davea.name
Wed Dec 12 16:35:07 CET 2012


On 12/12/2012 10:00 AM, inshu chauhan wrote:
> In this code :
>
> import cv
> g = open("PointCloudmitClass.txt", "w")
> image = cv.LoadImageM("Z:/modules/intensity_000001.tif",
> cv.CV_LOAD_IMAGE_UNCHANGED)
> print image
> for y in xrange(0,image.height):
>     for x in xrange(0,image.width):
>         color = image[y,x]
>         if color == (0.0,0.0,0.0):
>             continue
>         else :
>
>             if color == (0.0,255.0,0.0):
>                 classification = 1
>             elif color == (128.0, 0.0, 255.0):
>                 classification = 2
>             elif color == (255.0,0.0,0.0):
>                 classification = 3
>             elif color == (128.0, 128.0, 128.0):
>                 classification = 4
>             elif color == (128.0, 64.0, 0.0):
>                 classification = 5
>             elif color == (0.0, 0.0, 255.0):
>                 classification = 6
>             elif color == (255.0, 0.0, 255.0):
>                 classification = 7
>
>             print >> g, x , y , color, classification
>
>
> I am getting the following error..
>
> Traceback (most recent call last):
>   File "Z:\modules\Get_Classification.py", line 27, in <module>
>     print >> g, x , y , color, classification
> NameError: name 'classification' is not defined
>
> Its simple error of name but m not getting why it should come as I have
> already defined Classification in between if-else loop ??
>
if-else doesn't define a loop, but each of the for statements do.

You have defined a classification for 8 of the possible colors, leaving
millions of them undefined.  If the first time through the loop you
manage to hit one of those undefined ones, you'll have no value for
classification.  So you get an exception.

Worse, if you manage to get past that first pixel with a valid
classification, then for remaining pixels, you'll be using the last
'valid' classification encountered.  This is the kind of "quiet failure"
that programmers dread.  Something that seems to work, but isn't even close.

If you're going to print (to file) on each iteration through the loop
(except 0,0,0), you need to make sure there's always a valid value.  So
you need at least one more classification value, and an else clause to
assign it, as ChrisA pointed out.

Do you have a reason for treating (0,0,0) specially?  When that value is
seen, the logic skips the print as well, since continue skips to the
next loop iteration.

Are you really getting floating point values, or are they always going
to be equal to an integer?  Those if/elif statements might be a problem
if you ever need to compare to a value like (128.4, 255.0, 255.0).

-- 

DaveA




More information about the Python-list mailing list