我在 pygame 表面上有一個矩形區域。我想將該區域轉換為 opencv 影像物件(不保存到檔案),以便僅對該矩形區域進行進一步的影像處理。我怎樣才能做到這一點?
selected_area = mysurface.subsurface((x,y,w,h))
img_array=numpy.array(pygame.surfarray.array2d(selected_area))
#image_object = ..... ?
gray = cv2.cvtColor(image_object, cv2.COLOR_BGR2GRAY)
cv2.imshow("test",gray)
uj5u.com熱心網友回復:
實際上,一個cv2影像只是一個三維numpy陣列。第一個維度是高度,第二個維度是寬度,第三個維度是藍色、綠色、紅色的通道數。
用于
import pygame
import cv2, numpy
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
def pygameSurfaceToCv2Image(mysurface, x, y, w, h):
selected_area = mysurface.subsurface((x, y, w, h))
img_array = numpy.array(pygame.surfarray.pixels3d(selected_area))
image_object = numpy.transpose(img_array, (1, 0, 2))
#image_object[:, :, [0, 2]] = image_object[:, :, [2, 0]]
image_object = cv2.cvtColor(image_object, cv2.COLOR_RGB2BGR)
return image_object
apple_surf = pygame.image.load("Apple1.bmp")
image_object = pygameSurfaceToCv2Image(apple_surf, 20, 20, 200, 120)
gray = cv2.cvtColor(image_object, cv2.COLOR_BGR2GRAY)
cv2.imshow("apple subsurface", image_object)
cv2.imshow("gray apple subsurface", gray)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(0)
window.blit(image, image.get_rect(center = window.get_rect().center))
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/495956.html
