2013-01-11 20 views
0

我有一个非常奇怪的问题与Pygame,它让我难倒了最后几个(好,更像是5个小时)。有用于制作照片马赛克的免费程序,但自从我早期用VB5修补以来,我就想写我自己的版本。你知道那是怎么回事我有很多很酷的部分,用于加载源图像,查找颜色平均值和所有内容。但在这里,我困惑和困惑。所以非常困惑和困惑。Pygame与奇怪的变量问题 - 几个变量不断增加原因不明

这部分程序将一个'目标图像'(将由小的源图像组成)转换为其他源图像将尝试匹配并最终替换的较小的颜色块。但由于某种原因,块的大小随着每次迭代而不断增加。我尝试了很多不同的东西,我不得不通过脚本去删除一些东西,并在发布之前添加更多评论。

目标img是一个1280x800的随机谷歌图片,但任何其他图片的工作原理应该是一样的。注意随着每个块的Y向大小增加,并且X大小随着新行的增加而增加。我硬编码为纯色矩形的设置大小(横跨2像素,比我使用的小得多),但无论出于何种原因,这种情况持续增加。现在第一行blits非常小,很难看清楚。这很快就会改变。 **这里是我正在使用的图像的链接(http://www.travelimg.org/wallpapers/2012/01/iceland-golden-falls-druffix-europe-golden-falls-golden-falls -iceland-natur-waterfall-waterfalls-800x1280.jpg),但其他更改为target.jpg的图片/大小也应该这样做。

如果任何人都可以指出我在正确的方向,将不胜感激。我想用完美的12x12纯色块来覆盖整个源图片。我无法弄清楚这些块的大小是如何改变的。

import pygame 
import os 
from time import sleep 

okformats = ['png','jpg','bmp','pcx','tif','lbm','pbm','pgm','ppm','xpm'] 

targetimg = 'C:\\Python27\\mosaic\\target.jpg' 

if targetimg[-3:] not in okformats: 
    print 'That format is unsupported, get ready for some errors...' 
else: 
    print 'Loading...' 


pygame.init() 
screen = pygame.display.set_mode((100,100)) #picked a size just to start it out 
clock = pygame.time.Clock() #possibly not needed in this script 

targetpic = pygame.image.load(targetimg).convert() 

targetrect = targetpic.get_rect() #returns something like [0,0,1280,800] 
targetsize = targetrect[2:] 
targetw = targetrect[2] 
targeth = targetrect[3] 

numpicsx = 100 #number of pictures that make up the width 
sourceratio = 1 #testing with square pics for now 
picxsize = targetw/numpicsx 
numpicsy = targeth/(picxsize*sourceratio) 
picysize = targeth/numpicsy 


print 'Blitting target image' 
screen = pygame.display.set_mode(targetsize) 
screen.fill((255,255,255)) #set to white in case of transparency 
screen.blit(targetpic,(0,0)) 

#update screen 
pygame.display.update() 
pygame.display.flip() 
clock.tick(30) 

SLOWDOWN = .1 #temp slow down to watch it 

print numpicsx #here are some print statements just to show all the starting values are correct 
print numpicsy 
print '---' 
print picxsize 
print picysize 

sleep(1) 

for x in xrange(numpicsx): 

    for y in xrange(numpicsy): 
    currentrect = [x*picxsize,y*picysize,x*picxsize+picxsize,y*picysize+picysize] 

    avgc = pygame.transform.average_color((targetpic), currentrect) #average color 
    avgc = avgc[:3] #drops out the alpha if there is one 

    pygame.draw.rect(screen, avgc, currentrect) 
    #pygame.draw.rect(screen, avgc, (currentrect[0],currentrect[1],currentrect[0]+2,currentrect[1]+2)) #hard coded 2s (rather than 12s in this case) to help pin point the problem 

    pygame.display.update() 
    pygame.display.flip() 
    clock.tick(30) #probably not needed 

    sleep(SLOWDOWN) 


print 'Done./nSleeping then quitting...' 
sleep(3) 

pygame.quit() 

回答

0

我的一位朋友看了我的代码,并告诉我这个问题。我认为绘制的矩形格式是(x1,y1,x2,y2),但它实际上是(x,y,宽度,高度)。这是新的行:

currentrect = [X * picxsize,Y * picysize,picxsize,picysize]

我也下降了clock.tick(30)线,以加快它的所有行动。