Drawing a rectangle inside a two-dimensional numpy array

I have a 2D numpy array containing separate data from each sensor pixel. The image is displayed in a graphical interface with a live tape from the camera. I want to draw a rectangle above the image to distinguish the area of โ€‹โ€‹the screen. It seems pretty simple to draw a rectangle that is parallel to the side of the image, but in the end I want to be able to rotate the rectangle. How do I know which pixels cover a rectangle when it is rotated?

+4
arrays numpy draw shape
source share
1 answer

You can use the Python image library if you don't mind dependency. If for a 2D array numpy data and an array of poly coordinates of a polygon (with shape (n, 2)), this will draw a polygon filled with the value 0 in the array:

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

There is a separate demo here:

 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() 

This script generates this graph:

enter image description here

+9
source share

All Articles