I have written some code to posterize an image in python.
I am looping through and getting the red, green, blue values separately. Is there a way to simplify this?
The hurdle I have is that each RGB value needs to be dealt with separately and cannot figure out a way to examine each pixel's values for RGB and change them, without making it more cumbersome than it is below.
This version works:
def posterize(pic):
w=getWidth(pic)
h=getHeight(pic)
newPic=makeEmptyPicture(w,h)
for x in range (0,w):
for y in range (0,h):
p=getPixel(pic,x,y)
newPxl=getPixel(newPic,x,y)
r=getRed(p)
g=getGreen(p)
b=getBlue(p)
if (r<64):
newR= 31
if (r>63 and r<128):
newR= 95
if (r>127 and r<192):
newR= 159
if (r>191 and r<256):
newR= 223
if (g<64):
newG= 31
if (g>63 and g<128):
newG= 95
if (g>127 and g<192):
newG= 159
if (g>191 and g<256):
newG= 223
if (b<64):
newB= 31
if (b>63 and b<128):
newB= 95
if (b>127 and b<192):
newB= 159
if (b>191 and b<256):
newB= 223
setColor(newPxl, makeColor(newR,newG,newB))
return (newPic)
This is the new code I have, but it is not changing the values for RGB.
def posterize(pic):
w=getWidth(pic)
h=getHeight(pic)
newPic=makeEmptyPicture(w,h)
for x in range (0,w):
for y in range (0,h):
p=getPixel(pic,x,y)
newPxl=getPixel(newPic,x,y)
r=getRed(p)
g=getGreen(p)
b=getBlue(p)
Value = [r,g,b]
for i in Value:
if (i<64 ):
i = 31
if (i>63 and i<128):
i= 95
if (i>127 and i<192):
i = 159
if (i>191 and i<256):
i = 223
setColor(newPxl,makeColor(r,g,b))
return (newPic)
With some guidance on where my logic was faulty. I solved the problem.
def posterize(pic):
w=getWidth(pic)
h=getHeight(pic)
newPic=makeEmptyPicture(w,h)
for x in range (0,w):
for y in range (0,h):
p=getPixel(pic,x,y)
newPxl=getPixel(newPic,x,y)
r=getRed(p)
g=getGreen(p)
b=getBlue(p)
r = int( posterizeColor(r))
g = int( posterizeColor(g))
b =int( posterizeColor(b))
setColor(newPxl, makeColor(r,g,b) )
return (newPic)
def posterizeColor(i):
if (i<64 ):
return 31
if (i>63 and i<128):
return 95
if (i>127 and i<192):
return 159
if (i>191 and i<256):
return 223