Write the function randomCollage(pic) which copies pic to 5 random locations in “7inX95in.jpg”

StackOverflow https://stackoverflow.com/questions/19755871

Question

My code seems to be copying every column to different locations, but I am not sure where to move the rand.int function; i get an error when it is anywhere else. Here is my current code:

def randomCollage(pic, count):
  pic = makePicture(getMediaPath(pic))
  canv = makePicture(getMediaPath(r"7inX95in.jpg"))
  startX = 0
  startY = 0
  endX = getWidth(canv) - getWidth(pic)
  endY = getHeight(canv) - getHeight(pic) 

  for count in range (0, count):
    targetX = random.randint(startX, endX)  
    for sourceX in range(0, getWidth(pic)):   
      targetY = random.randint(startY, endY)
      for sourceY in range(0, getHeight(pic)):
        color = getColor(getPixel(pic, sourceX, sourceY))
        setColor(getPixel(canv, targetX, targetY), color)
        targetY = targetY + 1
      targetX = targetX + 1

  explore(canv)
  return(canv)
Was it helpful?

Solution

You need a random base location for each of the image copies, but from there, the rows and columns must be in order. That base is best seen as the top,left corner and you should pick it outside the loops so it doesn't change during the pixel copy operation. Try something like:

targetX = random.randint(startX, endX)  
targetY = random.randint(startY, endY)
for count in range (0, count):
    for sourceX in range(0, getWidth(pic)):   
        for sourceY in range(0, getHeight(pic)):
            color = getColor(getPixel(pic, sourceX, sourceY))
            setColor(getPixel(canv, targetX+sourceX, targetY+sourceY), color)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top