Question

I'm trying to write a simple algorithm to halve the size of a picture, it seems to make sense to me, but I'm probably missing something obvious here, and was wondering if anyone can point me in the right direction.

a = pickAFile()
b = makePicture(a)
c = getWidth(b)
d = getHeight(b)
e = (c * 3) / 4
f = (d * 3) / 4
canvas = makeEmptyPicture(e,f)
sourceX = 1
for targetX in range (1, c):
  sourceY = 1
  for targetY in range (1, d):
    color = getColor(getPixel(b, sourceX, sourceY))
    setColor(getPixel(canvas, targetX, targetY), color)
    sourceY = sourceY + 2
    sourceX = sourceX + 2
show(canvas)
show(b)

EDIT: When I try to run it as it is now, I get a index out of bounds error for the for loops.

No correct solution

OTHER TIPS

To start with the dimensions of canvas should be half the original image. So you should change

e = (c * 3) / 4
f = (d * 3) / 4

to

e = c / 2
f = d / 2

Secondly the for loops are meant to iterate from the the first pixel of the new image to the the last. Please change the following

for targetX in range (1, c):

to

for targetX in range (1, e):

and

for targetY in range (1, d):

to

for targetY in range (1, f):

The next problem is that you increment the variable sourceX inside the inner for loop. You will need to change the indent for this line code so it is part of the outer for loop

The complete code should look like this

a = pickAFile()
b = makePicture(a)
c = getWidth(b)
d = getHeight(b)
e = c / 2
f = d / 2
canvas = makeEmptyPicture(e,f)
sourceX = 1
for targetX in range (1, e):
  sourceY = 1
  for targetY in range (1, f):
    color = getColor(getPixel(b, sourceX, sourceY))
    setColor(getPixel(canvas, targetX, targetY), color)
    sourceY = sourceY + 2
  sourceX = sourceX + 2
show(canvas)
show(b)

The last thing I recommend is for you choose more meaningful names for your variables. Nameing c and e, sourceWidth and targetWidth respectively would have helped you identify the problem with the for loops a lot easier. It would have also taken you less time to type a few extra keys then the time spent trying to find the problems within the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top