# How to edit pixel values of color image in SageMath?

I would like to change pixel values in a color image with Sagemath. I can do the same in python, but my program contains some parts which can not be done with python. Here are the codes for SageMath:

MWE:

from PIL import Image
img=Image.open('image.pgm')
#pxls=img.getdata()
print pxl[0,0]


When I compile thse codes with sage, error occurs :

"  File "smmm.sage.py", line 8, in <module>
print pxl[_sage_const_0 ,_sage_const_0 ]
TypeError: an integer is required
"


How can I fix this?

edit retag close merge delete

Sort by ยป oldest newest most voted

This is because Sage's preparser transforms the 0 in px1[0,0] into Sage's integers, while the object pxl is expecting Python's integers. The solution is to force the conversion to Python's integers via int():

pxl[int(0),int(0)]


More generally to check what Sage's preparser is doing with things you type, use the preparse command:

sage: preparse("pxl[0,0]")
'pxl[Integer(0),Integer(0)]'


(Integer() is for Sage's integers, while int() is for Python's integers).

more

( 2018-10-11 14:28:44 +0200 )edit

Or you can use r (for "raw") to avoid conversion to a Sage Integer:

pxl[0r, 0r]


If you do pxl[int(0),int(0)], the preparser turns the Python int 0 into a Sage Integer and it is then transformed back into a Python Integer.

If you use the raw indicator, conversion to a Sage integer is avoided.

( 2018-10-13 00:49:03 +0200 )edit

## Stats

Seen: 247 times

Last updated: Oct 11 '18