2012-09-28 4 views
4

센서의 각 픽셀에서 개별 데이터를 포함하는 2D numpy 배열이 있습니다. 이미지는 GUI에서 카메라의 라이브 피드와 함께 표시됩니다. 화면의 영역을 구별하기 위해 이미지 위에 직사각형을 그릴 수 있어야합니다. 그것은 이미지의 측면에 평행 한 사각형을 그리는 것이 매우 간단하지만 결국 사각형을 회전시킬 수 있기를 원합니다. 사각형이 회전 할 때 어떤 픽셀을 가리는 지 어떻게 알 수 있습니까?2D numpy 배열 내부에 사각형 그리기

+1

를 내가 열거 한 배열의 nstead? – user1696811

답변

9

종속성에 신경 쓰지 않는다면 Python Imaging Library를 사용할 수 있습니다. 차원 NumPy와 배열 data, 다각형 좌표 배열 poly 감안할 (모양을 (N, 2))이 배열에서 값 0으로 채워진 다각형을 그리는 것 여기

img = Image.fromarray(data) 
draw = ImageDraw.Draw(img) 
draw.polygon([tuple(p) for p in poly], fill=0) 
new_data = np.asarray(img) 

있어 독립된 데모 :

import numpy as np 
import matplotlib.pyplot as plt 

# Python Imaging Library imports 
import Image 
import ImageDraw 


def get_rect(x, y, width, height, angle): 
    rect = np.array([(0, 0), (width, 0), (width, height), (0, height), (0, 0)]) 
    theta = (np.pi/180.0) * angle 
    R = np.array([[np.cos(theta), -np.sin(theta)], 
        [np.sin(theta), np.cos(theta)]]) 
    offset = np.array([x, y]) 
    transformed_rect = np.dot(rect, R) + offset 
    return transformed_rect 


def get_data(): 
    """Make an array for the demonstration.""" 
    X, Y = np.meshgrid(np.linspace(0, np.pi, 512), np.linspace(0, 2, 512)) 
    z = (np.sin(X) + np.cos(Y)) ** 2 + 0.25 
    data = (255 * (z/z.max())).astype(int) 
    return data 


if __name__ == "__main__": 
    data = get_data() 

    # Convert the numpy array to an Image object. 
    img = Image.fromarray(data) 

    # Draw a rotated rectangle on the image. 
    draw = ImageDraw.Draw(img) 
    rect = get_rect(x=120, y=80, width=100, height=40, angle=30.0) 
    draw.polygon([tuple(p) for p in rect], fill=0) 
    # Convert the Image data to a numpy array. 
    new_data = np.asarray(img) 

    # Display the result using matplotlib. (`img.show()` could also be used.) 
    plt.imshow(new_data, cmap=plt.cm.gray) 
    plt.show() 

이 스크립트는이 플롯 생성) (나는 Gtk.DrawingArea를 사용하는 것이 더 쉬울 수 있습니다 생각하고

enter image description here