【问题标题】:Write the function randomCollage(pic) which copies pic to 5 random locations in “7inX95in.jpg”编写函数 randomCollage(pic) 将 pic 复制到“7inX95in.jpg”中的 5 个随机位置
【发布时间】:2013-11-03 17:39:14
【问题描述】:

我的代码似乎将每一列复制到不同的位置,但我不确定将 rand.int 函数移到哪里;当它在其他任何地方时,我得到一个错误。 这是我当前的代码:

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)

【问题讨论】:

  • 您预计会发生什么,以及正在发生什么?
  • 我希望将图片复制到画布上的 5 个随机位置。目前它在随机位置返回带有一堆线条的画布。
  • 好的——我想我明白了。看看下面的代码是否有帮助。做到这一点的方法不止一种。

标签: python random copy multimedia


【解决方案1】:

每个图像副本都需要一个随机的基本位置,但是从那里开始,行和列必须是有序的。该基础最好被视为左上角,您应该在循环之外选择它,这样它就不会在像素复制操作期间发生变化。尝试类似:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多