写一个可以人物图像为边缘填充绘制词云图的python代码
时间: 2024-06-12 11:04:18 浏览: 111
以下是一个可以将人物头像作为边缘填充绘制词云图的Python代码示例:
首先,需要安装必要的库:
```python
!pip install wordcloud
!pip install matplotlib
!pip install numpy
!pip install Pillow
!pip install requests
!pip install imageio
```
然后,可以先定义一个函数,用于获取人物头像的图片:
```python
import requests
from PIL import Image
import numpy as np
import os
import io
import imageio
def get_image(url):
response = requests.get(url)
img = Image.open(io.BytesIO(response.content)).convert("RGBA")
img_arr = np.array(img)
return img_arr
```
接下来,定义一个函数,用于绘制词云图:
```python
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
def generate_wordcloud(text, mask_image):
stopwords = set(STOPWORDS)
wc = WordCloud(background_color="white", max_words=2000, mask=mask_image,
stopwords=stopwords, contour_width=3, contour_color='firebrick')
wc.generate(text)
plt.figure(figsize=(10, 10))
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()
```
最后,可以调用函数,生成词云图:
```python
url = 'https://avatars.githubusercontent.com/u/16923247?v=4'
img_arr = get_image(url)
text = "Python is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991. An interpreted language, Python has a design philosophy which emphasizes code readability (notably using whitespace indentation to delimit code blocks rather than curly brackets or keywords), and a syntax which allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. The language provides constructs intended to enable writing clear programs on both a small and large scale."
generate_wordcloud(text, img_arr)
```
这样就可以生成一个以人物头像为边缘填充的词云图了。
阅读全文