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

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

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)
有帮助吗?

解决方案

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top