python根据图片生成词云图 python词云图
在当今的数字化时代,文本数据常常以图片的形式出现,如社交媒体上的截图、新闻报道的图片等。对于这些图片,我们可能希望将其中的文字提取出来并生成词云图,以便更好地理解和分析。下面我们将介绍如何使用Python根据图片生成词云图。
一、使用OCR(光学字符识别)提取文本
首先,我们需要使用OCR技术将图片中的文字提取出来。Python有很多OCR库可供选择,如Tesseract和OpenCV。
- 使用Tesseract OCR
Tesseract是一个由Google开发的开源OCR引擎,可以识别多种语言。要使用Tesseract,您需要安装pytesseract库。安装方法:pip install pytesseract
接下来,您可以使用以下代码将图片中的文字提取出来:import cv2import pytesseract# 加载图像并转换为灰度图像image = cv2.imread('image.png')gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# 使用Tesseract OCR提取文本text = pytesseract.image_to_string(gray, lang='eng')print(text)
- 使用OpenCV OCR
OpenCV库也提供了OCR功能。要使用OpenCV OCR,您需要安装pycocotools库。安装方法:pip install pycocotools
接下来,您可以使用以下代码将图片中的文字提取出来:import cv2import pycocotools.mask as maskUtilsfrom pycocotools.coco import COCOimport numpy as npimport skimage.io as ioimport matplotlib.pyplot as pltfrom skimage import color, exposureimport cv2 as cvfrom PIL import Imageimport pytesseract# 加载图像并转换为灰度图像image = cv2.imread('image.png')gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# 使用Tesseract OCR提取文本并转换为分词形式text = pytesseract.image_to_string(Image.fromarray(np.uint8(gray)))[1:-1].split() # [1:-1] 是为了去掉结果字符串两端的空格和换行符,split() 是将字符串按照空格分割成单词列表。print(text)
二、生成词云图
接下来,我们可以使用Python的wordcloud库生成词云图。安装方法:pip install wordcloud
以下是一个简单的示例代码:
```python
from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import pytesseract
import cv2 as cv
from pycocotools.coco import COCO
import pycocotools.mask as maskUtils
import os
import json
import re
from collections import Counter
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import accuracy_score
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
import string
from collections import Counter
import random
from nltk import ngrams
from nltk.corpus import stopwords
from nltk.stem import wordnet
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import words to install the nltk libraries download it and install in python thn make python set the download location thn follow this order but with sudo (It might require root privileges) 1- sudo apt-get install python3-pip 2- sudo pip3 install nltk 3- sudo