梵高星空是荷蘭畫家梵高於1889年在法國聖雷米製作的一幅油畫。這幅畫展現了夜晚的天空,擁有引人入勝的細節和豐富的色彩。在這篇文章中,我們將介紹如何使用Python繪製梵高星空。
一、安裝必備庫
要用Python畫梵高星空,需要安裝一些必備的庫,包括matplotlib、numpy和Pillow。matplotlib和numpy是Python中重要的科學計算和繪圖庫,而Pillow是Python中常用的圖像處理庫。
!pip install matplotlib
!pip install numpy
!pip install Pillow
二、準備數據
在開始繪製之前,我們需要準備作為數據的星空圖像。我們可以從Google等搜索引擎中獲取梵高星空的圖像,然後使用Pillow庫將其讀入。對於這個指南,我已經準備好了一個名為“starry_night.jpg”的圖像文件。
from PIL import Image
import numpy as np
# 讀取圖像
img = Image.open('starry_night.jpg')
# 將圖像轉換為numpy數組
arr = np.array(img)
三、繪製星空
繪製星空的代碼分為4個步驟,即準備畫布、繪製背景、繪製星星和顯示結果。在這裡,我們使用matplotlib庫來完成這些步驟。
準備畫布
我們首先創建一個圖形對象,並添加一個子繪圖區,以便在其中繪製星空。我們還將設置子繪圖區的大小,使其與原始圖像的分辨率相同。
import matplotlib.pyplot as plt
# 創建圖形對象和子繪圖區
fig, ax = plt.subplots(figsize=arr.shape[:2][::-1]/100,
dpi=100)
# 將子繪圖區設置為黑色背景
ax.set_facecolor('black')
繪製背景
我們使用imshow()函數將原始圖像繪製到子繪圖區的背景中。如果圖像的顏色太亮太亮,可以使用set_distance()函數調整它們的屬性。
# 將原始圖像繪製為背景圖像
ax.imshow(arr)
# 調整亮度和對比度
ax.set_adjustable('datalim')
ax.set_aspect('equal')
ax.margins(0, 0)
繪製星星
為了繪製星星,我們需要在畫布上生成一些點,每個點都設置為隨機位置和顏色。我們還可以調整這些點的大小和數量,以實現所需的視覺效果。在代碼中,我們使用numpy庫中的random函數生成隨機點,然後使用matplotlib中的scatter函數將它們繪製到畫布上。
# 生成隨機點
num_stars = 1000
size_range = (5, 10)
colors = ['#8d9db6', '#ffe262', '#ff7473', '#fe8a71']
x = np.random.randint(0, arr.shape[1], num_stars)
y = np.random.randint(0, arr.shape[0], num_stars)
s = np.random.randint(*size_range, num_stars)
c = np.random.choice(colors, num_stars)
# 在畫布上繪製星星
ax.scatter(x, y, s=s, c=c)
顯示結果
最後,我們可以使用show()函數顯示繪製後的結果。
# 顯示結果
plt.show()
四、完成結果
在完成了所有這些步驟後,我們現在就可以得到一張令人印象深刻的梵高星空圖像。關於完整的代碼,請看下面:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
# 讀取圖像
img = Image.open('starry_night.jpg')
# 將圖像轉換為numpy數組
arr = np.array(img)
# 創建圖形對象和子繪圖區
fig, ax = plt.subplots(figsize=arr.shape[:2][::-1]/100,
dpi=100)
# 將子繪圖區設置為黑色背景
ax.set_facecolor('black')
# 將原始圖像繪製為背景圖像
ax.imshow(arr)
# 調整亮度和對比度
ax.set_adjustable('datalim')
ax.set_aspect('equal')
ax.margins(0, 0)
# 生成隨機點
num_stars = 1000
size_range = (5, 10)
colors = ['#8d9db6', '#ffe262', '#ff7473', '#fe8a71']
x = np.random.randint(0, arr.shape[1], num_stars)
y = np.random.randint(0, arr.shape[0], num_stars)
s = np.random.randint(*size_range, num_stars)
c = np.random.choice(colors, num_stars)
# 在畫布上繪製星星
ax.scatter(x, y, s=s, c=c)
# 顯示結果
plt.show()
原創文章,作者:SBKGB,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/371602.html