This time, I will generate a gradation image with python by referring to this article.
This time, we will generate an image using two functions.
gradation_2d_color
def gradation_2d_color(start, stop, size, is_horizontal):
if is_horizontal:
return np.tile(np.linspace(start, stop, size[1]), (size[0], 1))
else:
return np.tile(np.linspace(start, stop, size[0]), (size[1], 1)).T
Using np.linspace, create a one-dimensional array of length height (or width) that stores the values of arithmetic progressions that divide the range from start to stop by the number of height (or width), and create this with np.tile. Creates a two-dimensional array of length width (or height) that is duplicated and stored by the number of width (or height). ・ Start: Start pixel value ・ Stop: End pixel value ・ Size: Image size [height, width] ・ Is_horizontal: True → Horizontal gradation change / False → Vertical gradation change
gradation_3d_img
def gradation_3d_img(start_list, stop_list, size, is_horizontal_list):
result = np.zeros((size[0], size[1], len(start_list)), dtype=np.float)
for i, (start, stop, is_horizontal) in enumerate(zip(start_list, stop_list, is_horizontal_list)):
result[:, :, i] = gradation_2d_color(start, stop, size, is_horizontal)
return result
Pass the list corresponding to each rgb. The first element is the r component, the second element is the g component, and the third element is the b component. -Start_list: List of start pixel values -Stop_list: List of end pixel values ・ Size: List of image sizes ・ Is_horizontal_list: List of changing directions
Use these functions to generate a gradient image.
main
size = [400,500] #height, width
#Horizontally black → white
img = gradation_3d_img([0,0,0], [255,255,255], size, [True,True,True])
img = img.astype(np.uint8)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imwrite('out.png', img)
I tried other parameters with various values, with the image size set to (400,500).
rgb (0,0,0)
→ rgb (255,255,255)
--Direction of change of rgb: [→, →, →]rgb (0,0,0)
→ rgb (255,255,255)
--Direction of change of rgb: [↓, ↓, ↓]rgb (0,255,255)
→ rgb (255,255,255)
--Direction of change of rgb: [→, →, →]rgb (255,0,0)
→ rgb (0,255,255)
--Direction of change of rgb: [→, →, →]rgb (0,0,0)
→ rgb (255,255,255)
--Direction of change of rgb: [↓, →, →]rgb (0,0,0)
→ rgb (255,255,255)
--Direction of change of rgb: [↓, ↓, →]This gradation is expressed using np.linspace which generates arithmetic progression. I think you can express the gradation in the sense that the numerical value changes continuously. However, another question has arisen that the gradation change can be expressed numerically. Next time I will write about it.
Recommended Posts