6

我正在尝试从图片的右上角到左下角对角线绘制平行线。我希望它看起来像这样(可爱的油漆图片)

诊断油漆图片

def diagTopLBottomR():
  pic=makePicture(pickAFile())
  w=getWidth(pic)
  h=getHeight(pic)
  x1=0
  y1=0
  x2=0
  y2=0
  i=0
  while i<11:
    x1=10*i
    y2=10*i
    i+=1
    for y in range (y1,y2):
      x = (y-y1)*(x2-x1)/(y2-y1) +x1
      px=getPixel(pic,x,y)
      color=makeColor(0,0,0)
      setColor(px, color)
  x3=0
  y3=h
  x4=w
  y4=0
  j=0
  while j<10:
    x3=10*j
    y4=10*j
    j+=1
    for y in range (y3,y4):
      x = (y-y3)*(x4-x3)/(y4-y3) +x3
      px=getPixel(pic,x,y)
      color=makeColor(0,0,0)
      setColor(px, color)

  return(pic)

您会注意到x3 要么是最大值,导致超出范围异常,要么 y 范围将从更高的值开始,即 (y3>y4) 并且不能反向工作,或者当我减少它时。这就像一个悖论。

第一个循环正在工作,无论我尝试什么,我都无法让第二个循环工作。这就是我要结束的。

诊断线

有任何想法吗?谢谢。


编辑

我已经玩过范围,并且在第二个循环中没有得到任何结果,如上图所示的超出范围异常。

我努力了:

  x3=0
  y3=h
  x4=w
  y4=0
  j=0
  while j<10:
    x3=10*j
    y4=10*j
    j+=1
    for x in range (x3,x4):
      y = (x-x3)*(y4-y3)/(x4-x3) +y3

从这里偷了独角兽。

4

4 回答 4

8

在第一部分中,y1设置为 0 并y2在循环中从 0 增加,所以y1 < y2. 这很好,因为你使用

for y in range (y1,y2)

在第二部分中,y3设置为h(我猜在你的情况下为 128)并y4从循环中的 0 增加,所以y3 > y4. 这不好,因为您使用

for y in range (y3,y4)

您可以通过提供range()第三个参数来尝试向后退一步,该参数指示步长为 -1。或者您可以切换y3y4(注意这对您的其余代码的影响)。

于 2013-08-05T17:49:32.610 回答
5

range() assumes the first parameter is less than the second parameter, and it goes in an ascending order. You have:

for y in range (y3,y4):

where y3=h and y4=0 (on the first pass). Since y3 > y4, this loop does nothing. You can use either:

for y in range(y4,y3):

or

for y in range(y3,y4,-1):
于 2013-08-05T17:49:09.717 回答
5

在第二个循环中,y3大于(或等于)y4。所以,试试range (y4,y3)

于 2013-08-05T17:54:19.300 回答
2

我通过制作px=getPixel(pic,x,y-1) 和使用减少 y 范围的建议答案来解决它。

def diagTopLBottomR():
  pic=makePicture(pickAFile())
  w=getWidth(pic)
  h=getHeight(pic)
  x1=0
  y1=0
  x2=0
  y2=0
  i=0
  while i<10:
    x1=10*i
    y2=10*i
    i+=1
    for y in range (y1,y2):
      x = (y-y1)*(x2-x1)/(y2-y1) +x1
      px=getPixel(pic,x,y)
      color=makeColor(0,0,0)
      setColor(px, color)
  x3=0
  y3=h
  x4=w
  y4=0
  j=0
  while j<10:
    x3=10*j
    y4=10*j
    j+=1
    for y in range (y3,y4,-1):#change here
      x = abs((y-y3)*(x4-x3)/(y4-y3) +x3)
      px=getPixel(pic,x,y-1)#change here
      color=makeColor(0,0,0)
      setColor(px, color)

  return(pic)

图片

于 2013-08-05T18:19:19.970 回答