4
我有一個2D numpy陣列,其中包含傳感器每個像素的單個數據。圖像通過相機的實時反饋顯示在GUI中。我希望能夠在圖像上繪製一個矩形,以便區分屏幕的某個區域。繪製一個與圖像邊平行的矩形似乎很簡單,但我最終希望能夠旋轉矩形。如何知道當矩形旋轉時矩形覆蓋哪些像素?在二維numpy陣列內繪製一個矩形
我有一個2D numpy陣列,其中包含傳感器每個像素的單個數據。圖像通過相機的實時反饋顯示在GUI中。我希望能夠在圖像上繪製一個矩形,以便區分屏幕的某個區域。繪製一個與圖像邊平行的矩形似乎很簡單,但我最終希望能夠旋轉矩形。如何知道當矩形旋轉時矩形覆蓋哪些像素?在二維numpy陣列內繪製一個矩形
如果您不介意依賴關係,則可以使用Python Imaging Library。給定一個2D 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()我而不是一個numpy數組? – user1696811