本文提供了一种获取微信的联系人列表的方法,步骤如下:
- 给微信的联系人加上备注
- 登录微信windows pc客户端,打开通讯录管理
- 调整窗口大小,让备注这一列的内容完整显示
- 使用FSCapture工具截取该窗口的长图(选中窗口,点击捕捉滚动窗口按钮)
- 用画图工具打开上面保存的长图
- 记录下第一行联系人前面复选框的左上、右下坐标点【查看下面的图例】
- 记录下第一行联系人备注文本区域左上、右下坐标点【查看下面的图例】
- 运行以下脚本,实现以下功能:
- 用复选框区域的特征,通过模板匹配的方式找到所有的行坐标
- 再结合上面备注区域的坐标和大小,裁剪出每个联系人备注区域的图片
- 通过百度OCR提取图片中文本,保存到文本文件中
- 可优化的点: 将裁剪出来的图像拼接到一张大图上,可节约ocr api的请求次数
代码
import cv2
from PIL import Image
import requests
import base64
import time
import numpy as np
def baiu_ocr_predict(filepath):
from aip import AipOcr
APP_ID = ''
API_KEY = ''
SECRET_KEY = ''
client = AipOcr(APP_ID,API_KEY,SECRET_KEY)
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
image = get_file_content(filepath)
res = client.basicAccurate(image)
try:
if "words_result" in res:
return res["words_result"][-1]['words']
return "None"
except:
return "Error"
def findCenterOfLine(img,template_lt,template_rb):
lt=template_lt
rb=template_rb
img_rgb = img[:,lt[0]:rb[0],:]
template = img[lt[1]:rb[1],lt[0]:rb[0],:]
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
method = cv2.TM_CCOEFF_NORMED
res = cv2.matchTemplate(img_gray, template_gray, method)
loc = np.where(res >= 0.5)
centers=[]
for pt in zip(*loc[::-1]):
centers.append(int(pt[1] + template_gray.shape[1]/2))
return centers
def main():
img=cv2.imread("img.png")
first_box_lt=(571,78) #第一行备注的左上角落坐标(需要修改)
first_box_rb=(890,129) #第一行备注的右下角落坐标(需要修改)
template_lt=(225,94) #第一个勾选框的左上角落坐标(需要修改)
template_rb=(240,109) #第一个勾选框的右下角落坐标(需要修改)
centers=findCenterOfLine(img,template_lt,template_rb) #找到所有行的中心
h,w,c=img.shape
box_h=first_box_rb[1]-first_box_lt[1]
box_w=first_box_rb[0]-first_box_lt[0]
fo=open("person.txt","w")
for idx,yoff in enumerate(centers):
x0=first_box_lt[0]
y0=yoff-int(box_h/2)
if y0+box_h>h:
break
ceil=img[y0:y0+box_h,x0:x0+box_w,:]
cv2.imwrite("tmp.jpg",ceil)
name=baiu_ocr_predict("tmp.jpg")
print(idx,name)
fo.write(f"{idx},{name}\n")
fo.flush()
time.sleep(1)
fo.close()
main()