|
| 1 | + |
| 2 | +import base64 |
| 3 | +from bs4 import BeautifulSoup as BS |
| 4 | +import baiduapi as bd |
| 5 | +import httpx |
| 6 | +from PIL import Image |
| 7 | +import io |
| 8 | +import difflib |
| 9 | +import datetime |
| 10 | + |
| 11 | + |
| 12 | +def grabImage(file=None): |
| 13 | + if file: |
| 14 | + image = Image.open(file) |
| 15 | + output_buffer = io.BytesIO() |
| 16 | + image.save(output_buffer, format='JPEG') |
| 17 | + return output_buffer.getvalue() |
| 18 | + else: |
| 19 | + # 获取并保存图片 直接从必应上获取 |
| 20 | + rsp = httpx.get("https://cn.bing.com/") |
| 21 | + bs = BS(rsp.content, "html.parser") |
| 22 | + bglink = bs.find("link").get("href") |
| 23 | + url = str(rsp.url) + bglink |
| 24 | + |
| 25 | + image = httpx.get(url).content |
| 26 | + return image |
| 27 | + |
| 28 | +def isINeed(image): |
| 29 | + # # 压缩图片 |
| 30 | + img = Image.open(io.BytesIO(image)) |
| 31 | + x, y = img.size |
| 32 | + x_s = round(x/2) |
| 33 | + y_s = int(y * x_s / x) |
| 34 | + out = img.resize((x_s, y_s), Image.ANTIALIAS) |
| 35 | + |
| 36 | + # 图片转码 |
| 37 | + output_buffer = io.BytesIO() |
| 38 | + out.save(output_buffer, format='JPEG') |
| 39 | + out.save(r"D:\abc.jpg") |
| 40 | + byte_data = output_buffer.getvalue() |
| 41 | + # 图片识别 |
| 42 | + result = bd.imageRecognition(byte_data) |
| 43 | + print("result:", result) |
| 44 | + # 结果分析 |
| 45 | + |
| 46 | + ## 计算特征 |
| 47 | + keywords = ['植物', '树', '天空', '阳光','霞光', '晚霞','海洋','大海','森林','湖泊','草原','沙漠','高山','瀑布'] |
| 48 | + score = 0 |
| 49 | + for r in result: |
| 50 | + # 进行对比 |
| 51 | + for k in keywords: |
| 52 | + root = r.get('keyword', '') |
| 53 | + ratio = difflib.SequenceMatcher(None, root, k).ratio() |
| 54 | + mscore = r.get('score') |
| 55 | + score += mscore*ratio |
| 56 | + print(" text:%s\t vs kwd:%s\tmscore:%f\tratio:%f\tresult:%f" % (root, k, mscore, ratio, mscore*ratio)) |
| 57 | + return score |
| 58 | + |
| 59 | +def run(test=False): |
| 60 | + filename = None |
| 61 | + if test: |
| 62 | + filename = r'C:\Users\alisx\Pictures\Saved Pictures1032781円.jpg' |
| 63 | + |
| 64 | + image = grabImage(filename) |
| 65 | + score = isINeed(image) |
| 66 | + if score > 0.5: |
| 67 | + with open(r"C:\Users\alisx\Pictures\Saved Pictures\bing_%s.jpg" % datetime.date.today(), 'wb') as f: |
| 68 | + f.write(image) |
| 69 | + |
| 70 | +if __name__ == '__main__': |
| 71 | + run() |
| 72 | + |
0 commit comments