Ni *_* Na 5 python user-interface pygame numpy
我从文件导入图像,该文件总是更新(总是以相同的文件名保存新图片),现在当文件中的图像更改时,我的 GUI 未更新必须更改页面或执行某些图像会更改的操作我的意思是更改显示. 但是我想实时更改显示的图像(每次更改文件中的图像时都会更改)
我写这样的代码:
def first():
# crop
img_crop = mpimg.imread('Crop.jpg')
#img_crop = numpy.load('bur.npy')
x = numpy.arange(10)
y = numpy.arange(20)
X, Y = numpy.meshgrid(x, y)
img_crop_re = cv2.resize(img_crop, dsize=(200,200), interpolation=cv2.INTER_CUBIC)
img_crop_ro = cv2.rotate(img_crop_re, cv2.ROTATE_90_COUNTERCLOCKWISE)
img_crop_flip = cv2.flip(img_crop_ro,0)
surf_crop = pygame.surfarray.make_surface(img_crop_flip)
# mask
img_mask = mpimg.imread('mask.jpg')
#img_mask = numpy.load('bur.npy')
x = numpy.arange(10,50)
y = numpy.arange(20,50)
X, Y = numpy.meshgrid(x, y)
img_mask_re = cv2.resize(img_mask, dsize=(200, 200), interpolation=cv2.INTER_CUBIC)
img_mask_ro = cv2.rotate(img_mask_re, cv2.ROTATE_90_COUNTERCLOCKWISE)
img_mask_flip = cv2.flip(img_mask_re,0)
surf_mask = pygame.surfarray.make_surface(img_mask_flip)
running = True
while running:
screen.fill((30,30,30))
screen.blit(surf_crop, (850, 360))
screen.blit(surf_mask, (1170, 360))
...
pygame.display.flip()
pygame.display.update()
mainClock.tick(60)
Run Code Online (Sandbox Code Playgroud)
理想情况下,除非图像已更改,否则您不想重新加载图像。一种快捷方式是检查图像文件的“上次更新”时间。
import os.path
IMAGE_PATH = "/path/to/image.jpg"
timestamp = os.path.getmtime( IMAGE_PATH )
Run Code Online (Sandbox Code Playgroud)
将其与图像加载器包装在一起:
class UpdatedImage:
def __init__( self, filename ):
self.filename = filename
self.last_update = 0 # trigger initial load
self.image = None # final surface
self.reLoadImage() # make sure we load once, first
def drawAt( self, window, position ):
""" Draw the image to the screen at the given position """
window.blit( self.image, position )
def reLoadImage( self ):
""" Load in the image iff it has changed on disk """
current_file_time = os.path.getmtime( self.filename )
if ( current_file_time > self.last_update ):
self.last_update = current_file_time
img_crop = mpimg.imread( self.filename )
x = numpy.arange(10)
y = numpy.arange(20)
X, Y = numpy.meshgrid(x, y)
img_crop_re = cv2.resize(img_crop, dsize=(200,200), interpolation=cv2.INTER_CUBIC)
img_crop_ro = cv2.rotate(img_crop_re, cv2.ROTATE_90_COUNTERCLOCKWISE)
img_crop_flip = cv2.flip(img_crop_ro,0)
self.image = pygame.surfarray.make_surface(img_crop_flip)
Run Code Online (Sandbox Code Playgroud)
这会给你一个主循环:
crop_image = UpdatedImage( "Crop.jpg" )
running = True
while running:
screen.fill((30,30,30))
crop_image.reLoadImage()
crop_image.drawAt( screen, ( 850, 360 ) )
# ...
Run Code Online (Sandbox Code Playgroud)
因此,虽然crop_image.reLoadImage()每帧都被调用,但它仅在磁盘上将来有修改时间的情况下加载图像。