我想使用 pygame 创建一堆简单的几何形状(彩色矩形、三角形、正方形...),然后分析它们的关系和特征。我第一次尝试turtle但显然这只是一个图形库,无法跟踪它创建的形状,我想知道 Pygame 是否也是如此。为了说明这一点,假设我有这个脚本:
# Import a library of functions called 'pygame'
import pygame
from math import pi
# Initialize the game engine
pygame.init()
# Define the colors we will use in RGB format
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
# Set the height and width of the screen
size = [800, 600]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Example code for the draw module")
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
while not done:
# This limits the while loop to a max of 10 times per second.
# Leave this out and we will use all CPU we can.
clock.tick(10)
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
screen.fill(WHITE)
# Draw a rectangle outline
pygame.draw.rect(screen, BLACK, [75, 10, 50, 20], 2)
# Draw a solid rectangle
pygame.draw.rect(screen, BLACK, [150, 10, 50, 20])
# Draw an ellipse outline, using a rectangle as the outside boundaries
pygame.draw.ellipse(screen, RED, [225, 10, 50, 20], 2)
# Draw a circle
pygame.draw.circle(screen, BLUE, [60, 250], 40)
# Go ahead and update the screen with what we've drawn.
# This MUST happen after all the other drawing commands.
pygame.display.flip()
# Be IDLE friendly
pygame.quit()
它创建了这个图像:
现在,假设我保存 Pygame 创建的图像。 Pygame 有没有办法从图像中检测形状、颜色和坐标?
最佳答案
PyGame 是一个游戏库 - 它有助于制作游戏的图形、音频和 Controller 。它不支持检测现有图像中的对象。
您想要的是 OpenCV(它具有 Python 绑定(bind)) - 这是为了“理解”有关图像的内容。
用于检测任何类型的形状(或边缘)的一种流行的数学算法是霍夫变换。您可以在这里阅读更多相关信息 - http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/hough_circle/hough_circle.html
OpenCV 内部有霍夫变换函数,非常有用。
<小时/>您可以尝试制作自己的霍夫变换代码并使用它......但是库使它更容易。
关于python - pygame可以识别简单的几何形状吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31444776/