首页 文章 精选 留言 我的

精选列表

搜索[博客系统],共10000篇文章
优秀的个人博客,低调大师

基于百度飞桨paddlepaddle的疫情可视化实战 |【大学生博客大赛】

百度paddlepaddle安装及疫情可视化实战 1. paddle安装可以参考官方文档 地址链接: https://www.paddlepaddle.org.cn/install/quick选择合适自己的方式进行安装 2. 疫情数据可视化 思路:通过爬虫得到数据并且通过pyecharts进行可视化 爬取丁香园公开的统计数据 上网的全过程: 普通用户打开浏览器 --> 往目标站点发送请求 --> 接收响应数据 --> 渲染到页面上。 爬虫程序模拟浏览器 --> 往目标站点发送请求 --> 接收响应数据 --> 提取有用的数据 --> 保存到本地/数据库。 爬虫的过程: 1.发送请求(requests模块) 2.获取响应数据(服务器返回) 3.解析并提取数据(re正则) 4.保存数据 我们用到了:request模块: requests是python实现的简单易用的HTTP库,官网地址:http://cn.python-requests.org/zh_CN/latest/ re模块: re模块是python用于匹配字符串的模块,该模块中提供的很多功能是基于正则表达式实现的, import json import re import requests import datetime today = datetime.date.today().strftime('%Y%m%d') #20200315 def crawl_dxy_data(): """ 爬取丁香园实时统计数据,保存到data目录下,以当前日期作为文件名,存JSON文件 """ response = requests.get('https://ncov.dxy.cn/ncovh5/view/pneumonia') #request.get()用于请求目标网站 print(response.status_code) # 打印状态码 try: url_text = response.content.decode() #更推荐使用response.content.deocde()的方式获取响应的html页面 #print(url_text) url_content = re.search(r'window.getAreaStat = (.*?)}]}catch', #re.search():扫描字符串以查找正则表达式模式产生匹配项的第一个位置 ,然后返回相应的match对象。 url_text, re.S) #在字符串a中,包含换行符\n,在这种情况下:如果不使用re.S参数,则只在每一行内进行匹配,如果一行没有,就换下一行重新开始; #而使用re.S参数以后,正则表达式会将这个字符串作为一个整体,在整体中进行匹配。 texts = url_content.group() #获取匹配正则表达式的整体结果 content = texts.replace('window.getAreaStat = ', '').replace('}catch', '') #去除多余的字符 json_data = json.loads(content) with open('data/' + today + '.json', 'w', encoding='UTF-8') as f: json.dump(json_data, f, ensure_ascii=False) except: print('<Response [%s]>' % response.status_code) def crawl_statistics_data(): """ 获取各个省份历史统计数据,保存到data目录下,存JSON文件 """ with open('data/'+ today + '.json', 'r', encoding='UTF-8') as file: json_array = json.loads(file.read()) statistics_data = {} for province in json_array: response = requests.get(province['statisticsData']) try: statistics_data[province['provinceShortName']] = json.loads(response.content.decode())['data'] except: print('<Response [%s]> for url: [%s]' % (response.status_code, province['statisticsData'])) with open("data/statistics_data.json", "w", encoding='UTF-8') as f: json.dump(statistics_data, f, ensure_ascii=False) if __name__ == '__main__': crawl_dxy_data() crawl_statistics_data() 运行以上代码,我们需要在代码同目录下创建data文件夹运行成功后,在data文件夹下能够得到两个文件分别是:statistics_data.json和一个今天日期的json 安装第三方库pyecharts Echarts 是一个由百度开源的数据可视化工具,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可。而 Python 是一门富有表达力的语言,很适合用于数据处理。当数据分析遇上数据可视化时,pyecharts 诞生了。pyecharts api可以参考:https://pyecharts.org/#/zh-cn/chart_api 使用 options 配置项,在 pyecharts 中,一切皆 Options。 主要分为全局配置组件和系列配置组件。 (1)系列配置项 set_series_opts(),可配置图元样式、文字样式、标签样式、点线样式等; (2)全局配置项 set_global_opts(),可配置标题、动画、坐标轴、图例等; pyecharts非常好用!!!我们通过pip安装 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyecharts 如果下载时出现断线和速度过慢的问题导致下载失败,可以尝试使用其他国内源当出现Successfully installed pyecharts-1.7.1 simplejson-3.17.0时我们就安装成功了 数据可视化地图 全国地图 import json import datetime from pyecharts.charts import Map from pyecharts import options as opts # 读原始数据文件 today = datetime.date.today().strftime('%Y%m%d') #20200315 datafile = 'data/'+ today + '.json' with open(datafile, 'r', encoding='UTF-8') as file: json_array = json.loads(file.read()) # 分析全国实时确诊数据:'confirmedCount'字段 china_data = [] for province in json_array: china_data.append((province['provinceShortName'], province['confirmedCount'])) china_data = sorted(china_data, key=lambda x: x[1], reverse=True) #reverse=True,表示降序,反之升序 print(china_data) # 全国疫情地图 # 自定义的每一段的范围,以及每一段的特别的样式。 pieces = [ {'min': 10000, 'color': '#540d0d'}, {'max': 9999, 'min': 1000, 'color': '#9c1414'}, {'max': 999, 'min': 500, 'color': '#d92727'}, {'max': 499, 'min': 100, 'color': '#ed3232'}, {'max': 99, 'min': 10, 'color': '#f27777'}, {'max': 9, 'min': 1, 'color': '#f7adad'}, {'max': 0, 'color': '#f7e4e4'}, ] labels = [data[0] for data in china_data] counts = [data[1] for data in china_data] m = Map() m.add("累计确诊", [list(z) for z in zip(labels, counts)], 'china') #系列配置项,可配置图元样式、文字样式、标签样式、点线样式等 m.set_series_opts(label_opts=opts.LabelOpts(font_size=12), is_show=False) #全局配置项,可配置标题、动画、坐标轴、图例等 m.set_global_opts(title_opts=opts.TitleOpts(title='全国实时确诊数据', subtitle='数据来源:丁香园'), legend_opts=opts.LegendOpts(is_show=False), visualmap_opts=opts.VisualMapOpts(pieces=pieces, is_piecewise=True, #是否为分段型 is_show=True)) #是否显示视觉映射配置 #render()会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件,也可以传入路径参数,如 m.render("mycharts.html") m.render(path='./data/数据.html') 这里代码都有完善的注释,就不拆解来讲了 ### 数据可视化湖北省地图 ```python import json import datetime from pyecharts.charts import Map from pyecharts import options as opts # 读原始数据文件 today = datetime.date.today().strftime('%Y%m%d') #20200315 datafile = 'data/'+ today + '.json' with open(datafile, 'r', encoding='UTF-8') as file: json_array = json.loads(file.read()) # 分析湖北省实时确诊数据 # 读入规范化的城市名称,用于规范化丁香园数据中的城市简称 with open('/home/aistudio/data/data24815/pycharts_city.txt', 'r', encoding='UTF-8') as f: defined_cities = [line.strip() for line in f.readlines()] def format_city_name(name, defined_cities): for defined_city in defined_cities: if len((set(defined_city) & set(name))) == len(name): name = defined_city if name.endswith('市') or name.endswith('区') or name.endswith('县') or name.endswith('自治州'): return name return name + '市' return None province_name = '湖北' for province in json_array: if province['provinceName'] == province_name or province['provinceShortName'] == province_name: json_array_province = province['cities'] hubei_data = [(format_city_name(city['cityName'], defined_cities), city['confirmedCount']) for city in json_array_province] hubei_data = sorted(hubei_data, key=lambda x: x[1], reverse=True) print(hubei_data) labels = [data[0] for data in hubei_data] counts = [data[1] for data in hubei_data] pieces = [ {'min': 10000, 'color': '#540d0d'}, {'max': 9999, 'min': 1000, 'color': '#9c1414'}, {'max': 999, 'min': 500, 'color': '#d92727'}, {'max': 499, 'min': 100, 'color': '#ed3232'}, {'max': 99, 'min': 10, 'color': '#f27777'}, {'max': 9, 'min': 1, 'color': '#f7adad'}, {'max': 0, 'color': '#f7e4e4'}, ] m = Map() m.add("累计确诊", [list(z) for z in zip(labels, counts)], '湖北') m.set_series_opts(label_opts=opts.LabelOpts(font_size=12), is_show=False) m.set_global_opts(title_opts=opts.TitleOpts(title='湖北省实时确诊数据', subtitle='数据来源:丁香园'), legend_opts=opts.LegendOpts(is_show=False), visualmap_opts=opts.VisualMapOpts(pieces=pieces, is_piecewise=True, is_show=True)) m.render(path='./data/湖北省数据.html') 增长趋势 on from pyecharts.charts import Line from pyecharts import options as opts # 读原始数据文件 datafile = 'data/statistics_data.json' with open(datafile, 'r', encoding='UTF-8') as file: json_dict = json.loads(file.read()) # 分析各省份2月1日至今的新增确诊数据:'confirmedIncr' statistics__data = {} for province in json_dict: statistics__data[province] = [] for da in json_dict[province]: if da['dateId'] >= 20200201: statistics__data[province].append(da['confirmedIncr']) # 获取日期列表 dateId = [str(da['dateId'])[4:6] + '-' + str(da['dateId'])[6:8] for da in json_dict['湖北'] if da['dateId'] >= 20200201] # 全国新增趋势 all_statis = np.array([0] * len(dateId)) for province in statistics__data: all_statis = all_statis + np.array(statistics__data[province]) all_statis = all_statis.tolist() # 湖北新增趋势 hubei_statis = statistics__data['湖北'] # 湖北以外的新增趋势 other_statis = [all_statis[i] - hubei_statis[i] for i in range(len(dateId))] line = Line() line.add_xaxis(dateId) line.add_yaxis("全国新增确诊病例", #图例 all_statis, #数据 is_smooth=True, #是否平滑曲线 linestyle_opts=opts.LineStyleOpts(width=4, color='#B44038'),#线样式配置项 itemstyle_opts=opts.ItemStyleOpts(color='#B44038', #图元样式配置项 border_color="#B44038", #颜色 border_width=10)) #图元的大小 line.add_yaxis("湖北新增确诊病例", hubei_statis, is_smooth=True, linestyle_opts=opts.LineStyleOpts(width=2, color='#4E87ED'), label_opts=opts.LabelOpts(position='bottom'), #标签在折线的底部 itemstyle_opts=opts.ItemStyleOpts(color='#4E87ED', border_color="#4E87ED", border_width=3)) line.add_yaxis("其他省份新增病例", other_statis, is_smooth=True, linestyle_opts=opts.LineStyleOpts(width=2, color='#F1A846'), label_opts=opts.LabelOpts(position='bottom'), #标签在折线的底部 itemstyle_opts=opts.ItemStyleOpts(color='#F1A846', border_color="#F1A846", border_width=3)) line.set_global_opts(title_opts=opts.TitleOpts(title="新增确诊病例", subtitle='数据来源:丁香园'), yaxis_opts=opts.AxisOpts(max_=16000, min_=1, type_="log", #坐标轴配置项 splitline_opts=opts.SplitLineOpts(is_show=True),#分割线配置项 axisline_opts=opts.AxisLineOpts(is_show=True)))#坐标轴刻度线配置项 line.render(path='./data/趋势图.html') 需要自己完成的饼状图 import json import datetime from pyecharts.charts import Map, Pie from pyecharts import options as opts # 读原始数据文件 today = datetime.date.today().strftime('%Y%m%d') #20200315 datafile = 'data/'+ today + '.json' with open(datafile, 'r', encoding='UTF-8') as file: json_array = json.loads(file.read()) # 分析全国实时确诊数据:'confirmedCount'字段 china_data = [] for province in json_array: china_data.append((province['provinceShortName'], province['confirmedCount'])) china_data = sorted(china_data, key=lambda x: x[1], reverse=True) #reverse=True,表示降序,反之升序 print(china_data) labels = [data[0] for data in china_data] counts = [data[1] for data in china_data] m = Pie(init_opts=opts.InitOpts(height='900px')) m.add("累计确诊", [list(z) for z in zip(labels, counts)], center=["50%", "60%"], radius=['0%', '40%']) #,)center=[100,50] m.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}", font_size=12), is_show=False) #全局配置项,可配置标题、动画、坐标轴、图例等 m.set_global_opts(title_opts=opts.TitleOpts(title='全国实时确诊数据', subtitle='数据来源:丁香园'), legend_opts=opts.LegendOpts(is_show=False, type_="scroll", pos_left="80%", orient="vertical"), ) #render()会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件,也可以传入路径参数,如 m.render("mycharts.html") m.render(path='./data/饼状图.html') over!!!

优秀的个人博客,低调大师

[python作业AI毕业设计博客]英文原版新书下载:Impractical Python Projects - 2019.Pdf

python测试开发项目实战-目录 python工具书籍下载-持续更新 python 3.7极速入门教程 - 目录 下载:Impractical Python Projects - 2019.Pdf Impractical Python Projects is a collection of fun and educational projects designed to entertain programmers while enhancing their Python skills. It picks up where the complete beginner books leave off, expanding on existing concepts and introducing new tools that you'll use every day. And to keep things interesting, each project includes a zany twist featuring historical incidents, pop culture references, and literary allusions. You'll flex your problem-solving skills and employ Python's many useful libraries to do things like:• Help James Bond crack a high-tech safe with a hill-climbing algorithm • Write haiku poems using Markov Chain Analysis• Use genetic algorithms to breed a race of gigantic rats• Crack the world's most successful military cipher using cryptanalysis• Derive the anagram, "I am Lord Voldemort" using linguistical sieves • Plan your parents' secure retirement with Monte Carlo simulation• Save the sorceress Zatanna from a stabby death using palingrams• Model the Milky Way and calculate our odds of detecting alien civilizations• Help the world's smartest woman win the Monty Hall problem argument• Reveal Jupiter's Great Red Spot using optical stacking• Save the head of Mary, Queen of Scots with steganography• Foil corporate security with invisible electronic ink Simulate volcanoes, map Mars, and more, all while gaining valuable experience using free modules like Tkinter, matplotlib, Cprofile, Pylint, Pygame, Pillow, and Python-Docx. Whether you're looking to pick up some new Python skills or just need a pick-me-up, you'll find endless educational, geeky fun with Impractical Python Projects. e-Books Highlight Edition1st Edition ISBN159327890X Posted on12/3/2018 FormatPdf Page Count426 Pages AuthorLee Vaughan, 参考资料 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 2018最佳人工智能机器学习工具书及下载(持续更新)

优秀的个人博客,低调大师

[雪峰磁针石博客]计算机视觉opcencv工具深度学习快速实战2 opencv快速入门

opencv基本操作 # -*- coding: utf-8 -*- # Author: xurongzhong#126.com wechat:pythontesting qq:37391319 # 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入) # qq群:144081101 591302926 567351477 # CreateDate: 2018-11-17 import imutils import cv2 # 读取图片信息 image = cv2.imread("jp.png") (h, w, d) = image.shape print("width={}, height={}, depth={}".format(w, h, d)) # 显示图片 cv2.imshow("Image", image) cv2.waitKey(0) # 访问像素 (B, G, R) = image[100, 50] print("R={}, G={}, B={}".format(R, G, B)) # 选取图片区间 ROI (Region of Interest) roi = image[60:160, 320:420] cv2.imshow("ROI", roi) cv2.waitKey(0) # 缩放 resized = cv2.resize(image, (200, 200)) cv2.imshow("Fixed Resizing", resized) cv2.waitKey(0) # 按比例缩放 r = 300.0 / w dim = (300, int(h * r)) resized = cv2.resize(image, dim) cv2.imshow("Aspect Ratio Resize", resized) cv2.waitKey(0) # 使用imutils缩放 resized = imutils.resize(image, width=300) cv2.imshow("Imutils Resize", resized) cv2.waitKey(0) # 顺时针旋转45度 center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, -45, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("OpenCV Rotation", rotated) cv2.waitKey(0) # 使用imutils旋转 rotated = imutils.rotate(image, -45) cv2.imshow("Imutils Rotation", rotated) cv2.waitKey(0) # 使用imutils无损旋转 rotated = imutils.rotate_bound(image, 45) cv2.imshow("Imutils Bound Rotation", rotated) cv2.waitKey(0) # apply a Gaussian blur with a 11x11 kernel to the image to smooth it, # useful when reducing high frequency noise 高斯模糊 # https://www.pyimagesearch.com/2016/07/25/convolutions-with-opencv-and-python/ blurred = cv2.GaussianBlur(image, (11, 11), 0) cv2.imshow("Blurred", blurred) cv2.waitKey(0) # 画框 output = image.copy() cv2.rectangle(output, (320, 60), (420, 160), (0, 0, 255), 2) cv2.imshow("Rectangle", output) cv2.waitKey(0) # 画圆 output = image.copy() cv2.circle(output, (300, 150), 20, (255, 0, 0), -1) cv2.imshow("Circle", output) cv2.waitKey(0) # 划线 output = image.copy() cv2.line(output, (60, 20), (400, 200), (0, 0, 255), 5) cv2.imshow("Line", output) cv2.waitKey(0) # 输出文字 output = image.copy() cv2.putText(output, "https://china-testing.github.io", (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2) cv2.imshow("Text", output) cv2.waitKey(0) 原图: 选取图片区间 ROI (Region of Interest) 缩放 按比例缩放 旋转 使用imutils无损旋转 高斯模糊 画框 画圆 划线 输出文字 执行时的输出 $ python opencv_tutorial_01.py width=600, height=322, depth=3 R=41, G=49, B=37 本节英文原版代码下载 关于旋转这块,实际上pillow做的更好。比如同样逆时针旋转90度。 opencv的实现: import imutils import cv2 image = cv2.imread("jp.png") rotated = imutils.rotate(image, 90) cv2.imshow("Imutils Rotation", rotated) cv2.waitKey(0) pillow的实现: from PIL import Image im = Image.open("jp.png") im2 = im.rotate(90, expand=True) im2.show() 更多参考: python库介绍-图像处理工具pillow中文文档-手册(2018 5.*) 参考资料 技术支持qq群144081101(代码和模型存放) 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 2018最佳人工智能机器学习工具书及下载(持续更新) 代码下载:https://itbooks.pipipan.com/fs/18113597-320636142 代码github地址:https://github.com/china-testing/python-api-tesing/tree/master/opencv_crash_deep_learning 识别俄罗斯方块 # -*- coding: utf-8 -*- # Author: xurongzhong#126.com wechat:pythontesting qq:37391319 # 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入) # qq群:144081101 591302926 567351477 # CreateDate: 2018-11-19 # python opencv_tutorial_02.py --image tetris_blocks.png import argparse import imutils import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Image", image) cv2.waitKey(0) # 转为灰度图 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("Gray", gray) cv2.waitKey(0) # 边缘检测 edged = cv2.Canny(gray, 30, 150) cv2.imshow("Edged", edged) cv2.waitKey(0) # 门限 thresh = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)[1] cv2.imshow("Thresh", thresh) cv2.waitKey(0) # 发现边缘 cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] output = image.copy() # loop over the contours for c in cnts: # draw each contour on the output image with a 3px thick purple # outline, then display the output contours one at a time cv2.drawContours(output, [c], -1, (240, 0, 159), 3) cv2.imshow("Contours", output) cv2.waitKey(0) # draw the total number of contours found in purple text = "I found {} objects!".format(len(cnts)) cv2.putText(output, text, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (240, 0, 159), 2) cv2.imshow("Contours", output) cv2.waitKey(0) # we apply erosions to reduce the size of foreground objects mask = thresh.copy() mask = cv2.erode(mask, None, iterations=5) cv2.imshow("Eroded", mask) cv2.waitKey(0) # 扩大 mask = thresh.copy() mask = cv2.dilate(mask, None, iterations=5) cv2.imshow("Dilated", mask) cv2.waitKey(0) # a typical operation we may want to apply is to take our mask and # apply a bitwise AND to our input image, keeping only the masked # regions mask = thresh.copy() output = cv2.bitwise_and(image, image, mask=mask) cv2.imshow("Output", output) cv2.waitKey(0) 原图和灰度图: 边缘检测 门限 轮廓 查找结果 腐蚀和扩张 屏蔽和位操作 串在一起执行 $ python opencv_tutorial_02.py --image tetris_blocks.png

优秀的个人博客,低调大师

[雪峰磁针石博客]数据分析工具pandas快速入门教程5-处理缺失数据

第5章 缺失数据 介绍 很少没有任何缺失值的数据集。 有许多缺失数据的表示。 在数据库中是NULL值,一些编程语言使用NA。缺失值可以是空字符串:''或者甚至是数值88或99等。Pandas显示缺失值为NaN。 本章将涵盖: 什么是缺失值 如何创建缺失值 如何重新编码并使用缺失值进行计算 什么是缺失值 可以从numpy中获得NaN值,在Python中看到缺失值使用几种方式显示:NaN,NAN或nan,他们都是相等的。 NaN不等于0或空字符串''。 In [1]: from numpy import NaN, NAN, nan In [2]: print(NaN == True, NaN == False, NaN == 0, NaN == '', sep='|') False|False|False|False In [3]: print(NaN == NaN, NaN == nan, NaN == NAN, nan == NAN, sep='|') False|False|False|False In [4]: import pandas as pd In [5]: print(pd.isnull(NaN), pd.isnull(nan), pd.isnull(NAN), sep='|') True|True|True In [6]: print(pd.notnull(NaN), pd.notnull(99), pd.notnull("https://china-testing.github.io"), sep='|') False|True|True 缺失值的来源 来自加载数据或数据处理 加载数据 当我们加载数据时,pandas会自动找到该缺少数据的单元格,并填充NaN值。在read_csv函数中,参数na_values, keep_default_na, na_filter用于处理缺失值。比如:na_values=[99]。na_filter设置为False,在读大文件时会提升性能。 5-1.py import pandas as pd visited_file = 'data/survey_visited.csv' print(pd.read_csv(visited_file)) print(pd.read_csv(visited_file, keep_default_na=False)) print(pd.read_csv(visited_file, na_values=[''], keep_default_na=False)) 执行结果 $ python3 5-1.py ident site dated 0 619 DR-1 1927-02-08 1 622 DR-1 1927-02-10 2 734 DR-3 1939-01-07 3 735 DR-3 1930-01-12 4 751 DR-3 1930-02-26 5 752 DR-3 NaN 6 837 MSK-4 1932-01-14 7 844 DR-1 1932-03-22 ident site dated 0 619 DR-1 1927-02-08 1 622 DR-1 1927-02-10 2 734 DR-3 1939-01-07 3 735 DR-3 1930-01-12 4 751 DR-3 1930-02-26 5 752 DR-3 6 837 MSK-4 1932-01-14 7 844 DR-1 1932-03-22 ident site dated 0 619 DR-1 1927-02-08 1 622 DR-1 1927-02-10 2 734 DR-3 1939-01-07 3 735 DR-3 1930-01-12 4 751 DR-3 1930-02-26 5 752 DR-3 NaN 6 837 MSK-4 1932-01-14 7 844 DR-1 1932-03-22 合并数据 import pandas as pd visited = pd.read_csv('data/survey_visited.csv') survey = pd.read_csv('data/survey_survey.csv') print(visited) print(survey) vs = visited.merge(survey, left_on='ident', right_on='taken') print(vs) 执行结果 $ python3 5-2.py ident site dated 0 619 DR-1 1927-02-08 1 622 DR-1 1927-02-10 2 734 DR-3 1939-01-07 3 735 DR-3 1930-01-12 4 751 DR-3 1930-02-26 5 752 DR-3 NaN 6 837 MSK-4 1932-01-14 7 844 DR-1 1932-03-22 taken person quant reading 0 619 dyer rad 9.82 1 619 dyer sal 0.13 2 622 dyer rad 7.80 3 622 dyer sal 0.09 4 734 pb rad 8.41 5 734 lake sal 0.05 6 734 pb temp -21.50 7 735 pb rad 7.22 8 735 NaN sal 0.06 9 735 NaN temp -26.00 10 751 pb rad 4.35 11 751 pb temp -18.50 12 751 lake sal 0.10 13 752 lake rad 2.19 14 752 lake sal 0.09 15 752 lake temp -16.00 16 752 roe sal 41.60 17 837 lake rad 1.46 18 837 lake sal 0.21 19 837 roe sal 22.50 20 844 roe rad 11.25 ident site dated taken person quant reading 0 619 DR-1 1927-02-08 619 dyer rad 9.82 1 619 DR-1 1927-02-08 619 dyer sal 0.13 2 622 DR-1 1927-02-10 622 dyer rad 7.80 3 622 DR-1 1927-02-10 622 dyer sal 0.09 4 734 DR-3 1939-01-07 734 pb rad 8.41 5 734 DR-3 1939-01-07 734 lake sal 0.05 6 734 DR-3 1939-01-07 734 pb temp -21.50 7 735 DR-3 1930-01-12 735 pb rad 7.22 8 735 DR-3 1930-01-12 735 NaN sal 0.06 9 735 DR-3 1930-01-12 735 NaN temp -26.00 10 751 DR-3 1930-02-26 751 pb rad 4.35 11 751 DR-3 1930-02-26 751 pb temp -18.50 12 751 DR-3 1930-02-26 751 lake sal 0.10 13 752 DR-3 NaN 752 lake rad 2.19 14 752 DR-3 NaN 752 lake sal 0.09 15 752 DR-3 NaN 752 lake temp -16.00 16 752 DR-3 NaN 752 roe sal 41.60 17 837 MSK-4 1932-01-14 837 lake rad 1.46 18 837 MSK-4 1932-01-14 837 lake sal 0.21 19 837 MSK-4 1932-01-14 837 roe sal 22.50 20 844 DR-1 1932-03-22 844 roe rad 11.25 用户输入 import pandas as pd from numpy import NaN, NAN, nan num_legs = pd.Series({'goat': 4, 'amoeba': nan}) print(num_legs) scientists = pd.DataFrame({'Name': ['Rosaline Franklin', 'William Gosset'], 'Occupation': ['Chemist', 'Statistician'], 'Born': ['1920-07-25', '1876-06-13'], 'Died': ['1958-04-16', '1937-10-16'], 'missing': [NaN, nan]}) print(scientists) scientists['missing'] = nan print(scientists) 执行结果 $ python3 5-3.py amoeba NaN goat 4.0 dtype: float64 Born Died Name Occupation missing 0 1920-07-25 1958-04-16 Rosaline Franklin Chemist NaN 1 1876-06-13 1937-10-16 William Gosset Statistician NaN Born Died Name Occupation missing 0 1920-07-25 1958-04-16 Rosaline Franklin Chemist NaN 1 1876-06-13 1937-10-16 William Gosset Statistician NaN 重新索引 5-4.py import pandas as pd from numpy import NaN, NAN, nan gapminder = pd.read_csv('data/gapminder.tsv', sep='\t') life_exp = gapminder.groupby(['year'])['lifeExp'].mean() print(life_exp) print(life_exp.reindex(range(2000, 2010))) 执行结果 year 1952 49.057620 1957 51.507401 1962 53.609249 1967 55.678290 1972 57.647386 1977 59.570157 1982 61.533197 1987 63.212613 1992 64.160338 1997 65.014676 2002 65.694923 2007 67.007423 Name: lifeExp, dtype: float64 year 2000 NaN 2001 NaN 2002 65.694923 2003 NaN 2004 NaN 2005 NaN 2006 NaN 2007 67.007423 2008 NaN 2009 NaN Name: lifeExp, dtype: float64 处理缺失数据 统计缺失数据 5-5.py import pandas as pd from numpy import NaN, NAN, nan import numpy as np ebola = pd.read_csv('data/country_timeseries.csv') print(ebola.head()) print(ebola.count()) num_rows = ebola.shape[0] print("num_rows") print(num_rows) num_missing = num_rows - ebola.count() print("num_missing:") print(num_missing) print(np.count_nonzero(ebola.isnull())) print(np.count_nonzero(ebola['Cases_Guinea'].isnull())) print(ebola.Cases_Guinea.value_counts(dropna=False).head()) 执行结果 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone \ 0 1/5/2015 289 2776.0 NaN 10030.0 1 1/4/2015 288 2775.0 NaN 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 NaN 8157.0 NaN 4 12/31/2014 284 2730.0 8115.0 9633.0 Cases_Nigeria Cases_Senegal Cases_UnitedStates Cases_Spain Cases_Mali \ 0 NaN NaN NaN NaN NaN 1 NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN NaN 3 NaN NaN NaN NaN NaN 4 NaN NaN NaN NaN NaN Deaths_Guinea Deaths_Liberia Deaths_SierraLeone Deaths_Nigeria \ 0 1786.0 NaN 2977.0 NaN 1 1781.0 NaN 2943.0 NaN 2 1767.0 3496.0 2915.0 NaN 3 NaN 3496.0 NaN NaN 4 1739.0 3471.0 2827.0 NaN Deaths_Senegal Deaths_UnitedStates Deaths_Spain Deaths_Mali 0 NaN NaN NaN NaN 1 NaN NaN NaN NaN 2 NaN NaN NaN NaN 3 NaN NaN NaN NaN 4 NaN NaN NaN NaN Date 122 Day 122 Cases_Guinea 93 Cases_Liberia 83 Cases_SierraLeone 87 Cases_Nigeria 38 Cases_Senegal 25 Cases_UnitedStates 18 Cases_Spain 16 Cases_Mali 12 Deaths_Guinea 92 Deaths_Liberia 81 Deaths_SierraLeone 87 Deaths_Nigeria 38 Deaths_Senegal 22 Deaths_UnitedStates 18 Deaths_Spain 16 Deaths_Mali 12 dtype: int64 num_rows 122 num_missing: Date 0 Day 0 Cases_Guinea 29 Cases_Liberia 39 Cases_SierraLeone 35 Cases_Nigeria 84 Cases_Senegal 97 Cases_UnitedStates 104 Cases_Spain 106 Cases_Mali 110 Deaths_Guinea 30 Deaths_Liberia 41 Deaths_SierraLeone 35 Deaths_Nigeria 84 Deaths_Senegal 100 Deaths_UnitedStates 104 Deaths_Spain 106 Deaths_Mali 110 dtype: int64 1214 29 NaN 29 86.0 3 495.0 2 112.0 2 390.0 2 Name: Cases_Guinea, dtype: int64 处理缺失数据 5-6.py import pandas as pd from numpy import NaN, NAN, nan import numpy as np ebola = pd.read_csv('data/country_timeseries.csv') print(ebola.iloc[0:10, 0:5]) print(ebola.fillna(0).iloc[0:10, 0:5]) # 前向填充 print(ebola.fillna(method='ffill').iloc[0:10, 0:5]) # 后向填充 print(ebola.fillna(method='bfill').iloc[0:10, 0:5]) print(ebola.interpolate().iloc[0:10, 0:5]) print(ebola.shape) ebola_dropna = ebola.dropna() print(ebola_dropna.shape) print(ebola_dropna) ebola['Cases_multiple'] = ebola['Cases_Guinea'] + ebola['Cases_Liberia'] + \ ebola['Cases_SierraLeone'] ebola_subset = ebola.loc[:, ['Cases_Guinea', 'Cases_Liberia', 'Cases_SierraLeone', 'Cases_multiple']] print(ebola_subset.head(n=10)) print(ebola.Cases_Guinea.sum(skipna = True)) print(ebola.Cases_Guinea.sum(skipna = False)) 执行结果 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone 0 1/5/2015 289 2776.0 NaN 10030.0 1 1/4/2015 288 2775.0 NaN 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 NaN 8157.0 NaN 4 12/31/2014 284 2730.0 8115.0 9633.0 5 12/28/2014 281 2706.0 8018.0 9446.0 6 12/27/2014 280 2695.0 NaN 9409.0 7 12/24/2014 277 2630.0 7977.0 9203.0 8 12/21/2014 273 2597.0 NaN 9004.0 9 12/20/2014 272 2571.0 7862.0 8939.0 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone 0 1/5/2015 289 2776.0 0.0 10030.0 1 1/4/2015 288 2775.0 0.0 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 0.0 8157.0 0.0 4 12/31/2014 284 2730.0 8115.0 9633.0 5 12/28/2014 281 2706.0 8018.0 9446.0 6 12/27/2014 280 2695.0 0.0 9409.0 7 12/24/2014 277 2630.0 7977.0 9203.0 8 12/21/2014 273 2597.0 0.0 9004.0 9 12/20/2014 272 2571.0 7862.0 8939.0 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone 0 1/5/2015 289 2776.0 NaN 10030.0 1 1/4/2015 288 2775.0 NaN 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 2769.0 8157.0 9722.0 4 12/31/2014 284 2730.0 8115.0 9633.0 5 12/28/2014 281 2706.0 8018.0 9446.0 6 12/27/2014 280 2695.0 8018.0 9409.0 7 12/24/2014 277 2630.0 7977.0 9203.0 8 12/21/2014 273 2597.0 7977.0 9004.0 9 12/20/2014 272 2571.0 7862.0 8939.0 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone 0 1/5/2015 289 2776.0 8166.0 10030.0 1 1/4/2015 288 2775.0 8166.0 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 2730.0 8157.0 9633.0 4 12/31/2014 284 2730.0 8115.0 9633.0 5 12/28/2014 281 2706.0 8018.0 9446.0 6 12/27/2014 280 2695.0 7977.0 9409.0 7 12/24/2014 277 2630.0 7977.0 9203.0 8 12/21/2014 273 2597.0 7862.0 9004.0 9 12/20/2014 272 2571.0 7862.0 8939.0 Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone 0 1/5/2015 289 2776.0 NaN 10030.0 1 1/4/2015 288 2775.0 NaN 9780.0 2 1/3/2015 287 2769.0 8166.0 9722.0 3 1/2/2015 286 2749.5 8157.0 9677.5 4 12/31/2014 284 2730.0 8115.0 9633.0 5 12/28/2014 281 2706.0 8018.0 9446.0 6 12/27/2014 280 2695.0 7997.5 9409.0 7 12/24/2014 277 2630.0 7977.0 9203.0 8 12/21/2014 273 2597.0 7919.5 9004.0 9 12/20/2014 272 2571.0 7862.0 8939.0 (122, 18) (1, 18) Date Day Cases_Guinea Cases_Liberia Cases_SierraLeone \ 19 11/18/2014 241 2047.0 7082.0 6190.0 Cases_Nigeria Cases_Senegal Cases_UnitedStates Cases_Spain Cases_Mali \ 19 20.0 1.0 4.0 1.0 6.0 Deaths_Guinea Deaths_Liberia Deaths_SierraLeone Deaths_Nigeria \ 19 1214.0 2963.0 1267.0 8.0 Deaths_Senegal Deaths_UnitedStates Deaths_Spain Deaths_Mali 19 0.0 1.0 0.0 6.0 Cases_Guinea Cases_Liberia Cases_SierraLeone Cases_multiple 0 2776.0 NaN 10030.0 NaN 1 2775.0 NaN 9780.0 NaN 2 2769.0 8166.0 9722.0 20657.0 3 NaN 8157.0 NaN NaN 4 2730.0 8115.0 9633.0 20478.0 5 2706.0 8018.0 9446.0 20170.0 6 2695.0 NaN 9409.0 NaN 7 2630.0 7977.0 9203.0 19810.0 8 2597.0 NaN 9004.0 NaN 9 2571.0 7862.0 8939.0 19372.0 84729.0 nan 参考资料 技术支持qq群144081101 591302926 567351477 钉钉免费群21745728 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 源码下载 本文英文版书籍下载

优秀的个人博客,低调大师

[雪峰磁针石博客]flask构建自动化测试平台6-交互式犯罪地图

6-交互式犯罪地图 本章将介绍以下主题: mysql 创建犯罪地图 本文最新版本 代码地址 安装mysql # apt-get install mysql-server # pip3 install pymysql # python db_setup.py # 创建数据库 dbconfig.py test = False db_user = 'root' db_password = '654321_' db_setup.py import pymysql import dbconfig connection = pymysql.connect(host='localhost', user=dbconfig.db_user, passwd=dbconfig.db_password) try: with connection.cursor() as cursor: sql = "CREATE DATABASE IF NOT EXISTS crimemap" cursor.execute(sql) sql = """CREATE TABLE IF NOT EXISTS crimemap.crimes ( id int NOT NULL AUTO_INCREMENT, latitude FLOAT(10,6), longitude FLOAT(10,6), date DATETIME, category VARCHAR(50), description VARCHAR(255), updated_at TIMESTAMP, PRIMARY KEY (id) )""" cursor.execute(sql) connection.commit() finally: connection.close() crimemap.py from dbhelper import DBHelper from flask import Flask from flask import render_template from flask import request app = Flask(__name__) DB = DBHelper() @app.route("/") def home(): try: data = DB.get_all_inputs() except Exception as e: print(e) data = None return render_template("home.html", data=data) @app.route("/add", methods=["POST"]) def add(): try: data = request.form.get("userinput") DB.add_input(data) except Exception as e: print(e) return home() @app.route("/clear") def clear(): try: DB.clear_all() except Exception as e: print(e) return home() if __name__ == '__main__': app.run(host='0.0.0.0',port=8000, debug=True) dbhelper.py import pymysql import dbconfig class DBHelper: def connect(self, database="crimemap"): return pymysql.connect(host='localhost', user=dbconfig.db_user, passwd=dbconfig.db_password, db=database) def get_all_inputs(self): connection = self.connect() try: query = "SELECT description FROM crimes;" with connection.cursor() as cursor: cursor.execute(query) return cursor.fetchall() finally: connection.close() def add_input(self, data): connection = self.connect() try: query = "INSERT INTO crimes (description) VALUES (%s);" with connection.cursor() as cursor: cursor.execute(query, data) connection.commit() finally: connection.close() def clear_all(self): connection = self.connect() try: query = "DELETE FROM crimes;" with connection.cursor() as cursor: cursor.execute(query) connection.commit() finally: connection.close() home.html <html> <body> <head> <title>Crime Map</title> </head> <h1>Crime Map</h1> <form action="/add" method="POST"> <input type="text" name="userinput"> <input type="submit" value="Submit"> </form> <a href="/clear">clear</a> {% for userinput in data %} <p>{{userinput}}</p> {% endfor %} </body> </html> 参考资料 本文相关书籍下载 讨论 钉钉免费群21745728 qq群144081101 567351477 本文涉及的python测试开发库 谢谢点赞! 本文代码地址

优秀的个人博客,低调大师

[雪峰磁针石博客]python库介绍-os.path: 平台独立的文件名操作

Title: python库介绍-os.path: 平台独立的文件名操作Date: 2018-03-25 19:20Category: pythonSlug: python3_lib_os.path 目的:文件名和路径解析,组合,测试等。 使用os.path模块中包含的函数编写代码以便在多个平台上处理文件非常简单。即使不打算在平台之间移植的程序也应该使用os.path来进行可靠的文件名解析。 解析路径 路径解析依赖于在os中定义的几个变量: os.sep - 路径各部分之间的分隔符(例如“/”或“\”)。 os.extsep - 文件名和文件扩展名之间的分隔符。 os.pardir - 上级目录(e.g., “..”)。 os.curdir - 当前目录 (e.g., “.”)。 split()函数将路径分成两个独立的部分,并返回包含结果的元组。元组的第二个元素是路径的最后一个元素,第一个元素是之前的所有元素。 # ospath_split.py import os.path PATHS = [ '/one/two/three', '/one/two/three/', '/', '.', '', ] for path in PATHS: print('{!r:>17} : {}'.format(path, os.path.split(path))) 执行结果 $ python3 ospath_split.py '/one/two/three' : ('/one/two', 'three') '/one/two/three/' : ('/one/two/three', '') '/' : ('/', '') '.' : ('', '.') '' : ('', '') basename()函数返回等价于split()第二部分的值。 import os.path PATHS = [ '/one/two/three', '/one/two/three/', '/', '.', '', ] for path in PATHS: print('{!r:>17} : {!r}'.format(path, os.path.basename(path))) 执行结果 $ python3 ospath_basename.py '/one/two/three' : 'three' '/one/two/three/' : '' '/' : '' '.' : '.' '' : '' 完整路径被分解到最后一个元素,无论是指文件还是目录。如果路径在目录分隔符(os.sep)中结束,则basename是空的。 dirname() 函数返回分割路径的第一部分: import os.path PATHS = [ '/one/two/three', '/one/two/three/', '/', '.', '', ] for path in PATHS: print('{!r:>17} : {!r}'.format(path, os.path.dirname(path))) 执行结果 $ python3 ospath_dirname.py '/one/two/three' : '/one/two' '/one/two/three/' : '/one/two/three' '/' : '/' '.' : '' '' : '' 将basename()的结果与dirname()结合起来得到原始路径。 splitext()工作方式类似于split(),但将扩展分隔符(而不是目录分隔符)的路径分开。 import os.path PATHS = [ 'filename.txt', 'filename', '/path/to/filename.txt', '/', '', 'my-archive.tar.gz', 'no-extension.', ] for path in PATHS: print('{!r:>21} : {!r}'.format(path, os.path.splitext(path))) 执行结果 $ python3 ospath_splitext.py 'filename.txt' : ('filename', '.txt') 'filename' : ('filename', '') '/path/to/filename.txt' : ('/path/to/filename', '.txt') '/' : ('/', '') '' : ('', '') 'my-archive.tar.gz' : ('my-archive.tar', '.gz') 'no-extension.' : ('no-extension', '.') 在查找扩展名时,只使用最后一次出现的os.extsep,所以如果文件名有多个扩展名,则将其分割结果保留在前缀的一部分。 commonprefix() 将路径列表作为参数,并返回表示所有路径中存在的公共前缀的单个字符串。该值可能表示实际上不存在的路径,并且路径分隔符不包含在考虑因素中,所以前缀可能不会停止在分隔符边界上。 import os.path paths = ['/one/two/three/four', '/one/two/threefold', '/one/two/three/', ] for path in paths: print('PATH:', path) print() print('PREFIX:', os.path.commonprefix(paths)) 执行结果 $ python3 ospath_commonprefix.py PATH: /one/two/three/four PATH: /one/two/threefold PATH: /one/two/three/ PREFIX: /one/two/three commonpath()则会考虑os.seq。 import os.path paths = ['/one/two/three/four', '/one/two/threefold', '/one/two/three/', ] for path in paths: print('PATH:', path) print() print('PREFIX:', os.path.commonpath(paths)) 执行结果 $ python3 ospath_commonpath.py PATH: /one/two/three/four PATH: /one/two/threefold PATH: /one/two/three/ PREFIX: /one/two 本文代码地址 本文最新版本地址 交流QQ群:python 测试开发 144081101 构建路径 除了将现有的路径分开之外,通常还需要从其他字符串构建路径。要将多个路径组件合并请使用join(): import os.path PATHS = [ ('one', 'two', 'three'), ('/', 'one', 'two', 'three'), ('/one', '/two', '/three'), ] for parts in PATHS: print('{} : {!r}'.format(parts, os.path.join(*parts))) 执行结果 $ python3 ospath_join.py ('one', 'two', 'three') : 'one/two/three' ('/', 'one', 'two', 'three') : '/one/two/three' ('/one', '/two', '/three') : '/three' 如果任何连接的参数以os.sep开始,则所有先前的参数都将被丢弃,新的参数将成为返回值的开始。 也可以使用包含可自动扩展的“可变”组件的路径。例如,expanduser() 将 ~转换为用户主目录的名称。 # ospath_expanduser.py import os.path for user in ['', 'andrew', 'nosuchuser']: lookup = '~' + user print('{!r:>15} : {!r}'.format( lookup, os.path.expanduser(lookup))) 执行结果 '~' : '/home/andrew' '~andrew' : '/home/andrew' '~nosuchuser' : '~nosuchuser' 如果找不到用户的主目录,则字符串将以不变的形式返回,如本示例中的〜nosuchuser一样。 expandvars()更通用,它展开路径中的所有shell环境变量。 # ospath_expandvars.py import os.path import os os.environ['MYVAR'] = 'VALUE' print(os.path.expandvars('/path/to/$MYVAR')) 执行结果 $ python3 ospath_expandvars.py /path/to/VALUE 规范化路径 使用join()或嵌入变量从不同的字符串汇编的路径可能会以额外的分隔符或相对路径组件结束。使用normpath()来清理它们: # ospath_normpath.py import os.path PATHS = [ 'one//two//three', 'one/./two/./three', 'one/../alt/two/three', ] for path in PATHS: print('{!r:>22} : {!r}'.format(path, os.path.normpath(path))) 执行结果 $ python3 ospath_normpath.py 'one//two//three' : 'one/two/three' 'one/./two/./three' : 'one/two/three' 'one/../alt/two/three' : 'alt/two/three' 要将相对路径转换为绝对文件名,请使用abspath()。 # ospath_abspath.py import os import os.path os.chdir('/usr') PATHS = [ '.', '..', './one/two/three', '../one/two/three', ] for path in PATHS: print('{!r:>21} : {!r}'.format(path, os.path.abspath(path))) 执行结果 $ python3 ospath_normpath.py 'one//two//three' : 'one/two/three' 'one/./two/./three' : 'one/two/three' 'one/../alt/two/three' : 'alt/two/three' 文件时间 除了使用路径之外,os.path还包括用于检索文件属性的函数,类似于os.stat()返回的函数: import os.path import time print('File :', __file__) print('Access time :', time.ctime(os.path.getatime(__file__))) print('Modified time:', time.ctime(os.path.getmtime(__file__))) print('Change time :', time.ctime(os.path.getctime(__file__))) print('Size :', os.path.getsize(__file__)) os.path.getatime()返回访问时间,os.path.getmtime()返回修改时间,os.path.getctime()返回创建时间。 os.path.getsize()返回文件中的数据量,用字节表示。 执行结果 $ python3 ospath_properties.py File : ospath_properties.py Access time : Fri Aug 26 16:38:05 2016 Modified time: Fri Aug 26 15:50:48 2016 Change time : Fri Aug 26 15:50:49 2016 Size : 481 测试文件 当程序遇到路径名时,通常需要知道路径是指文件,目录还是符号链接,以及是否存在。 os.path包含测试所有这些条件的函数。 import os.path FILENAMES = [ __file__, os.path.dirname(__file__), '/', './broken_link', ] for file in FILENAMES: print('File : {!r}'.format(file)) print('Absolute :', os.path.isabs(file)) print('Is File? :', os.path.isfile(file)) print('Is Dir? :', os.path.isdir(file)) print('Is Link? :', os.path.islink(file)) print('Mountpoint? :', os.path.ismount(file)) print('Exists? :', os.path.exists(file)) print('Link Exists?:', os.path.lexists(file)) print() 执行结果 $ ln -s /does/not/exist broken_link $ python3 ospath_tests.py File : 'ospath_tests.py' Absolute : False Is File? : True Is Dir? : False Is Link? : False Mountpoint? : False Exists? : True Link Exists?: True File : '' Absolute : False Is File? : False Is Dir? : False Is Link? : False Mountpoint? : False Exists? : False Link Exists?: False File : '/' Absolute : True Is File? : False Is Dir? : True Is Link? : False Mountpoint? : True Exists? : True Link Exists?: True File : './broken_link' Absolute : False Is File? : False Is Dir? : False Is Link? : True Mountpoint? : False Exists? : False Link Exists?: True 参考资料 本文最新版本地址 讨论 钉钉免费群21745728 qq群144081101 567351477 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载

优秀的个人博客,低调大师

[雪峰磁针石博客]计算机视觉opcencv工具深度学习快速实战1人脸识别

使用OpenCV提供的预先训练的深度学习面部检测器模型,可快速,准确的进行人脸识别。 2017年8月OpenCV 3.3正式发布,带来了高改进的“深度神经网络”(dnn deep neural networks)模块。该模块支持许多深度学习框架,包括Caffe,TensorFlow和Torch / PyTorch。 基于Caffe的面部检测器在这里。 需要两组文件: 定义模型体系结构的.prototxt文件 .caffemodel文件,包含实际图层的权重 权重文件不包含在OpenCV示例目录。 OpenCV深度学习面部检测器如何工作? # 模型下载:https://itbooks.pipipan.com/fs/18113597-320346529 # 代码存放:https://github.com/china-testing/python-api-tesing/tree/master/opencv_crash_deep_learning # 技术支持qq群144081101(代码和模型存放) # USAGE # python detect_faces.py --image rooster.jpg --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel # import the necessary packages import numpy as np import argparse import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image") ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file") ap.add_argument("-m", "--model", required=True, help="path to Caffe pre-trained model") ap.add_argument("-c", "--confidence", type=float, default=0.5, help="minimum probability to filter weak detections") args = vars(ap.parse_args()) # load our serialized model from disk print("[INFO] loading model...") net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"]) # load the input image and construct an input blob for the image # by resizing to a fixed 300x300 pixels and then normalizing it image = cv2.imread(args["image"]) (h, w) = image.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) # pass the blob through the network and obtain the detections and # predictions print("[INFO] computing object detections...") net.setInput(blob) detections = net.forward() # loop over the detections for i in range(0, detections.shape[2]): # extract the confidence (i.e., probability) associated with the # prediction confidence = detections[0, 0, i, 2] # filter out weak detections by ensuring the `confidence` is # greater than the minimum confidence if confidence > args["confidence"]: # compute the (x, y)-coordinates of the bounding box for the # object box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") # draw the bounding box of the face along with the associated # probability text = "{:.2f}%".format(confidence * 100) y = startY - 10 if startY - 10 > 10 else startY + 10 cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2) cv2.putText(image, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2) # show the output image cv2.imshow("Output", image) cv2.waitKey(0) 执行: $ python detect_faces.py --image rooster.jpg --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel 上面的面部有74.30%的置信度。 尽管OpenCV的Haar级联因缺少“直接”角度的面孔,但通过使用OpenCV的深度学习面部探测器,依然能够测到脸部。 再来看三个面孔的示例: python detect_faces.py --image iron_chic.jpg --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel 视频,视频流和网络摄像头应用人脸检测 # USAGE # python detect_faces_video.py --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel # import the necessary packages from imutils.video import VideoStream import numpy as np import argparse import imutils import time import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file") ap.add_argument("-m", "--model", required=True, help="path to Caffe pre-trained model") ap.add_argument("-c", "--confidence", type=float, default=0.5, help="minimum probability to filter weak detections") args = vars(ap.parse_args()) # load our serialized model from disk print("[INFO] loading model...") net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"]) # initialize the video stream and allow the cammera sensor to warmup print("[INFO] starting video stream...") vs = VideoStream(src=0).start() time.sleep(2.0) # loop over the frames from the video stream while True: # grab the frame from the threaded video stream and resize it # to have a maximum width of 400 pixels frame = vs.read() frame = imutils.resize(frame, width=400) # grab the frame dimensions and convert it to a blob (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) # pass the blob through the network and obtain the detections and # predictions net.setInput(blob) detections = net.forward() # loop over the detections for i in range(0, detections.shape[2]): # extract the confidence (i.e., probability) associated with the # prediction confidence = detections[0, 0, i, 2] # filter out weak detections by ensuring the `confidence` is # greater than the minimum confidence if confidence < args["confidence"]: continue # compute the (x, y)-coordinates of the bounding box for the # object box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") # draw the bounding box of the face along with the associated # probability text = "{:.2f}%".format(confidence * 100) y = startY - 10 if startY - 10 > 10 else startY + 10 cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 0, 255), 2) cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2) # show the output frame cv2.imshow("Frame", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): break # do a bit of cleanup cv2.destroyAllWindows() vs.stop() 执行: python detect_faces_video.py --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel 参考资料 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载 2018最佳人工智能机器学习工具书及下载(持续更新) 模型下载:https://itbooks.pipipan.com/fs/18113597-320346529 其他python人脸识别库介绍 python库介绍-face_recognition 人脸识别 可以命令识别人脸框。 $ face_detection --model cnn iron_chic.jpg iron_chic.jpg,79,422,243,258 iron_chic.jpg,146,272,310,108 iron_chic.jpg,194,144,330,7

优秀的个人博客,低调大师

[雪峰磁针石博客]selenium自动化测试工具python笔试面试项目实战5键盘操作

说明 本文参考答案基于Chrome,分辨率1920*1080,在其他环境表现可能会不同。本文代码地址 参考书籍下载: Learning Selenium Testing Tools with Python-2014.pdf Selenium自动化测试 基于 Python 语言 - 2018.pdf 上机实操: 在新的TAB打开连接 打开:https://china-testing.github.io/ 选择"数据分析"栏目的文章 按住"Ctrl+TAB"选择"python"栏目的文章 切换到新的标签"python" 关闭新的标签"python" 关闭浏览器 参考答案 #!/usr/bin/python3 # -*- coding: utf-8 -*- # 讨论钉钉免费群21745728 qq群144081101 567351477 # CreateDate: 2018-10-17 import time from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get("https://china-testing.github.io/") driver.implicitly_wait(30) driver.maximize_window() element = driver.find_element_by_link_text('数据分析') element.click() time.sleep(3) element = driver.find_element_by_link_text('python') ActionChains(driver).key_down(Keys.CONTROL).click(element).key_up( Keys.CONTROL).perform() time.sleep(3) driver.switch_to.window(driver.window_handles[1]) time.sleep(3) driver.close() # 关闭当前TAB time.sleep(3) driver.quit() 面试问答 driver.quit() 和 driver.close()有什么区别? 2.selenium中按下和松开键如何表示? 3.简述ActionChains类的作用? 上机实操: 验证悬浮提示内容 打开:http://jqueryui.com/tooltip/ 鼠标移动到上图的"Your age:" 确认悬浮提示内容为'We ask for your age only for statistical purposes.' 关闭浏览器 参考答案 #!/usr/bin/python3 # -*- coding: utf-8 -*- # 讨论钉钉免费群21745728 qq群144081101 567351477 # CreateDate: 2018-10-17 import unittest import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.webdriver.common.action_chains import ActionChains class ToolTipTest (unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get("http://jqueryui.com/tooltip/") self.driver.implicitly_wait(30) self.driver.maximize_window() def test_tool_tip(self): driver = self.driver frame_elm = driver.find_element_by_class_name('demo-frame') driver.switch_to.frame(frame_elm) time.sleep(3) age_field = driver.find_element_by_id('age') ActionChains(self.driver).move_to_element(age_field).perform() time.sleep(3) tool_tip_elm = WebDriverWait(self.driver, 10).until( expected_conditions.visibility_of_element_located(( By.CLASS_NAME, 'ui-tooltip-content'))) # verify tooltip message self.assertEqual('We ask for your age only for statistical purposes.', tool_tip_elm.text) time.sleep(3) def tearDown(self): self.driver.close() if __name__ == '__main__': unittest.main(verbosity=2) 面试问答 1.move_to_element()有什么用途? 上机实操: 双击改变颜色 打开:http://api.jquery.com/dblclick/ 双击上图蓝色的框,把颜色该变成黄色 参考答案 #!/usr/bin/python3 # -*- coding: utf-8 -*- # 讨论钉钉免费群21745728 qq群144081101 567351477 # CreateDate: 2018-10-18 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import unittest class DoubleClickTest (unittest.TestCase): URL = 'http://api.jquery.com/dblclick/' def setUp(self): self.driver = webdriver.Chrome() self.driver.get(self.URL) self.driver.maximize_window() def test_double_click(self): driver = self.driver frame = driver.find_element_by_tag_name('iframe') driver.switch_to.frame(frame) box = driver.find_element_by_tag_name('div') # verify color is Blue self.assertEqual('rgba(0, 0, 255, 1)', box.value_of_css_property('background-color')) ActionChains(driver).move_to_element( driver.find_element_by_tag_name('body')).perform() ActionChains(driver).double_click(box).perform() # verify Color is Yellow self.assertEqual('rgba(255, 255, 0, 1)', box.value_of_css_property('background-color')) def tearDown(self): self.driver.close() if __name__ == '__main__': unittest.main(verbosity=2) 面试问答 1.double_click()有什么用途? 2.rgba的含义? 上机实操: 在新的TAB打开连接 打开:http://jqueryui.com/resources/demos/droppable/default.html 拖动左边的框到右边 参考答案 #!/usr/bin/python3 # -*- coding: utf-8 -*- # 讨论钉钉免费群21745728 qq群144081101 567351477 # CreateDate: 2018-10-18 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import unittest class DragAndDropTest (unittest.TestCase): URL = 'http://jqueryui.com/resources/demos/droppable/default.html' def setUp(self) : self.driver = webdriver.Chrome() self.driver.get(self.URL) self.driver.maximize_window() def test_drag_and_drop(self): driver = self.driver source = driver.find_element_by_id('draggable') target = driver.find_element_by_id('droppable') ActionChains(self.driver).drag_and_drop(source, target).perform() self.assertEqual('Dropped!', target.text) def tearDown(self): self.driver.close() if __name__ == '__main__': unittest.main(verbosity=2) 面试问答 1.drag_and_drop()有什么用途? 参考资料 讨论 钉钉群21745728 qq群144081101 567351477 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载

优秀的个人博客,低调大师

[雪峰磁针石博客]python opencv3实例(对象识别和增强现实)1-图像几何转换

原书代码地址 在本章中,我们将学习如何应用酷的几何效果到图像。 知识点 如何安装OpenCV-Python 如何读取,显示和保存图像 如何转换到多个颜色空间 如何应用几何变换,例如平移,旋转,和缩放 如何使用仿射和投影变换来应用几何效果 本书英文版本:OpenCV 3.x with Python By Example 2nd 2018.pdf 更多opencv相关书籍:最佳人工智能图像处理工具OpenCV书籍下载 安装OpenCV-Python 安装 本教程基于python3,ubuntu 16,在windows环境可能可以运行。 Linux #!python pip3 install opencv-python Windows #!python pip install opencv-python 文档: [官网](http://docs.opencv.org/) [opencv-python官方文档](http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html) 读取显示和保存图片 01_reading_image.py 读取显示图片 import cv2 img = cv2.imread('./images/input.jpg') cv2.imshow('Input image', img) cv2.waitKey() 02_saving_image.py 保存为灰度图 import cv2 gray_img = cv2.imread('images/input.jpg', cv2.IMREAD_GRAYSCALE) cv2.imshow('Grayscale', gray_img) cv2.imwrite('images/output.jpg', gray_img) cv2.waitKey() 转换格式 03_convert_image_format.py In [1]: import cv2 In [2]: print([x for x in dir(cv2) if x.startswith('COLOR_')]) ['COLOR_BAYER_BG2BGR', 'COLOR_BAYER_BG2BGRA', 'COLOR_BAYER_BG2BGR_EA', 'COLOR_BAYER_BG2BGR_VNG', 'COLOR_BAYER_BG2GRAY', 'COLOR_BAYER_BG2RGB', 'COLOR_BAYER_BG2RGBA', 'COLOR_BAYER_BG2RGB_EA', 'COLOR_BAYER_BG2RGB_VNG', 'COLOR_BAYER_GB2BGR', 'COLOR_BAYER_GB2BGRA', 'COLOR_BAYER_GB2BGR_EA', 'COLOR_BAYER_GB2BGR_VNG', 'COLOR_BAYER_GB2GRAY', 'COLOR_BAYER_GB2RGB', 'COLOR_BAYER_GB2RGBA', 'COLOR_BAYER_GB2RGB_EA', 'COLOR_BAYER_GB2RGB_VNG', 'COLOR_BAYER_GR2BGR', 'COLOR_BAYER_GR2BGRA', 'COLOR_BAYER_GR2BGR_EA', 'COLOR_BAYER_GR2BGR_VNG', 'COLOR_BAYER_GR2GRAY', 'COLOR_BAYER_GR2RGB', 'COLOR_BAYER_GR2RGBA', 'COLOR_BAYER_GR2RGB_EA', 'COLOR_BAYER_GR2RGB_VNG', 'COLOR_BAYER_RG2BGR', 'COLOR_BAYER_RG2BGRA', 'COLOR_BAYER_RG2BGR_EA', 'COLOR_BAYER_RG2BGR_VNG', 'COLOR_BAYER_RG2GRAY', 'COLOR_BAYER_RG2RGB', 'COLOR_BAYER_RG2RGBA', 'COLOR_BAYER_RG2RGB_EA', 'COLOR_BAYER_RG2RGB_VNG', 'COLOR_BGR2BGR555', 'COLOR_BGR2BGR565', 'COLOR_BGR2BGRA', 'COLOR_BGR2GRAY', 'COLOR_BGR2HLS', 'COLOR_BGR2HLS_FULL', 'COLOR_BGR2HSV', 'COLOR_BGR2HSV_FULL', 'COLOR_BGR2LAB', 'COLOR_BGR2LUV', 'COLOR_BGR2Lab', 'COLOR_BGR2Luv', 'COLOR_BGR2RGB', 'COLOR_BGR2RGBA', 'COLOR_BGR2XYZ', 'COLOR_BGR2YCR_CB', 'COLOR_BGR2YCrCb', 'COLOR_BGR2YUV', 'COLOR_BGR2YUV_I420', 'COLOR_BGR2YUV_IYUV', 'COLOR_BGR2YUV_YV12', 'COLOR_BGR5552BGR', 'COLOR_BGR5552BGRA', 'COLOR_BGR5552GRAY', 'COLOR_BGR5552RGB', 'COLOR_BGR5552RGBA', 'COLOR_BGR5652BGR', 'COLOR_BGR5652BGRA', 'COLOR_BGR5652GRAY', 'COLOR_BGR5652RGB', 'COLOR_BGR5652RGBA', 'COLOR_BGRA2BGR', 'COLOR_BGRA2BGR555', 'COLOR_BGRA2BGR565', 'COLOR_BGRA2GRAY', 'COLOR_BGRA2RGB', 'COLOR_BGRA2RGBA', 'COLOR_BGRA2YUV_I420', 'COLOR_BGRA2YUV_IYUV', 'COLOR_BGRA2YUV_YV12', 'COLOR_BayerBG2BGR', 'COLOR_BayerBG2BGRA', 'COLOR_BayerBG2BGR_EA', 'COLOR_BayerBG2BGR_VNG', 'COLOR_BayerBG2GRAY', 'COLOR_BayerBG2RGB', 'COLOR_BayerBG2RGBA', 'COLOR_BayerBG2RGB_EA', 'COLOR_BayerBG2RGB_VNG', 'COLOR_BayerGB2BGR', 'COLOR_BayerGB2BGRA', 'COLOR_BayerGB2BGR_EA', 'COLOR_BayerGB2BGR_VNG', 'COLOR_BayerGB2GRAY', 'COLOR_BayerGB2RGB', 'COLOR_BayerGB2RGBA', 'COLOR_BayerGB2RGB_EA', 'COLOR_BayerGB2RGB_VNG', 'COLOR_BayerGR2BGR', 'COLOR_BayerGR2BGRA', 'COLOR_BayerGR2BGR_EA', 'COLOR_BayerGR2BGR_VNG', 'COLOR_BayerGR2GRAY', 'COLOR_BayerGR2RGB', 'COLOR_BayerGR2RGBA', 'COLOR_BayerGR2RGB_EA', 'COLOR_BayerGR2RGB_VNG', 'COLOR_BayerRG2BGR', 'COLOR_BayerRG2BGRA', 'COLOR_BayerRG2BGR_EA', 'COLOR_BayerRG2BGR_VNG', 'COLOR_BayerRG2GRAY', 'COLOR_BayerRG2RGB', 'COLOR_BayerRG2RGBA', 'COLOR_BayerRG2RGB_EA', 'COLOR_BayerRG2RGB_VNG', 'COLOR_COLORCVT_MAX', 'COLOR_GRAY2BGR', 'COLOR_GRAY2BGR555', 'COLOR_GRAY2BGR565', 'COLOR_GRAY2BGRA', 'COLOR_GRAY2RGB', 'COLOR_GRAY2RGBA', 'COLOR_HLS2BGR', 'COLOR_HLS2BGR_FULL', 'COLOR_HLS2RGB', 'COLOR_HLS2RGB_FULL', 'COLOR_HSV2BGR', 'COLOR_HSV2BGR_FULL', 'COLOR_HSV2RGB', 'COLOR_HSV2RGB_FULL', 'COLOR_LAB2BGR', 'COLOR_LAB2LBGR', 'COLOR_LAB2LRGB', 'COLOR_LAB2RGB', 'COLOR_LBGR2LAB', 'COLOR_LBGR2LUV', 'COLOR_LBGR2Lab', 'COLOR_LBGR2Luv', 'COLOR_LRGB2LAB', 'COLOR_LRGB2LUV', 'COLOR_LRGB2Lab', 'COLOR_LRGB2Luv', 'COLOR_LUV2BGR', 'COLOR_LUV2LBGR', 'COLOR_LUV2LRGB', 'COLOR_LUV2RGB', 'COLOR_Lab2BGR', 'COLOR_Lab2LBGR', 'COLOR_Lab2LRGB', 'COLOR_Lab2RGB', 'COLOR_Luv2BGR', 'COLOR_Luv2LBGR', 'COLOR_Luv2LRGB', 'COLOR_Luv2RGB', 'COLOR_M_RGBA2RGBA', 'COLOR_RGB2BGR', 'COLOR_RGB2BGR555', 'COLOR_RGB2BGR565', 'COLOR_RGB2BGRA', 'COLOR_RGB2GRAY', 'COLOR_RGB2HLS', 'COLOR_RGB2HLS_FULL', 'COLOR_RGB2HSV', 'COLOR_RGB2HSV_FULL', 'COLOR_RGB2LAB', 'COLOR_RGB2LUV', 'COLOR_RGB2Lab', 'COLOR_RGB2Luv', 'COLOR_RGB2RGBA', 'COLOR_RGB2XYZ', 'COLOR_RGB2YCR_CB', 'COLOR_RGB2YCrCb', 'COLOR_RGB2YUV', 'COLOR_RGB2YUV_I420', 'COLOR_RGB2YUV_IYUV', 'COLOR_RGB2YUV_YV12', 'COLOR_RGBA2BGR', 'COLOR_RGBA2BGR555', 'COLOR_RGBA2BGR565', 'COLOR_RGBA2BGRA', 'COLOR_RGBA2GRAY', 'COLOR_RGBA2M_RGBA', 'COLOR_RGBA2RGB', 'COLOR_RGBA2YUV_I420', 'COLOR_RGBA2YUV_IYUV', 'COLOR_RGBA2YUV_YV12', 'COLOR_RGBA2mRGBA', 'COLOR_XYZ2BGR', 'COLOR_XYZ2RGB', 'COLOR_YCR_CB2BGR', 'COLOR_YCR_CB2RGB', 'COLOR_YCrCb2BGR', 'COLOR_YCrCb2RGB', 'COLOR_YUV2BGR', 'COLOR_YUV2BGRA_I420', 'COLOR_YUV2BGRA_IYUV', 'COLOR_YUV2BGRA_NV12', 'COLOR_YUV2BGRA_NV21', 'COLOR_YUV2BGRA_UYNV', 'COLOR_YUV2BGRA_UYVY', 'COLOR_YUV2BGRA_Y422', 'COLOR_YUV2BGRA_YUNV', 'COLOR_YUV2BGRA_YUY2', 'COLOR_YUV2BGRA_YUYV', 'COLOR_YUV2BGRA_YV12', 'COLOR_YUV2BGRA_YVYU', 'COLOR_YUV2BGR_I420', 'COLOR_YUV2BGR_IYUV', 'COLOR_YUV2BGR_NV12', 'COLOR_YUV2BGR_NV21', 'COLOR_YUV2BGR_UYNV', 'COLOR_YUV2BGR_UYVY', 'COLOR_YUV2BGR_Y422', 'COLOR_YUV2BGR_YUNV', 'COLOR_YUV2BGR_YUY2', 'COLOR_YUV2BGR_YUYV', 'COLOR_YUV2BGR_YV12', 'COLOR_YUV2BGR_YVYU', 'COLOR_YUV2GRAY_420', 'COLOR_YUV2GRAY_I420', 'COLOR_YUV2GRAY_IYUV', 'COLOR_YUV2GRAY_NV12', 'COLOR_YUV2GRAY_NV21', 'COLOR_YUV2GRAY_UYNV', 'COLOR_YUV2GRAY_UYVY', 'COLOR_YUV2GRAY_Y422', 'COLOR_YUV2GRAY_YUNV', 'COLOR_YUV2GRAY_YUY2', 'COLOR_YUV2GRAY_YUYV', 'COLOR_YUV2GRAY_YV12', 'COLOR_YUV2GRAY_YVYU', 'COLOR_YUV2RGB', 'COLOR_YUV2RGBA_I420', 'COLOR_YUV2RGBA_IYUV', 'COLOR_YUV2RGBA_NV12', 'COLOR_YUV2RGBA_NV21', 'COLOR_YUV2RGBA_UYNV', 'COLOR_YUV2RGBA_UYVY', 'COLOR_YUV2RGBA_Y422', 'COLOR_YUV2RGBA_YUNV', 'COLOR_YUV2RGBA_YUY2', 'COLOR_YUV2RGBA_YUYV', 'COLOR_YUV2RGBA_YV12', 'COLOR_YUV2RGBA_YVYU', 'COLOR_YUV2RGB_I420', 'COLOR_YUV2RGB_IYUV', 'COLOR_YUV2RGB_NV12', 'COLOR_YUV2RGB_NV21', 'COLOR_YUV2RGB_UYNV', 'COLOR_YUV2RGB_UYVY', 'COLOR_YUV2RGB_Y422', 'COLOR_YUV2RGB_YUNV', 'COLOR_YUV2RGB_YUY2', 'COLOR_YUV2RGB_YUYV', 'COLOR_YUV2RGB_YV12', 'COLOR_YUV2RGB_YVYU', 'COLOR_YUV420P2BGR', 'COLOR_YUV420P2BGRA', 'COLOR_YUV420P2GRAY', 'COLOR_YUV420P2RGB', 'COLOR_YUV420P2RGBA', 'COLOR_YUV420SP2BGR', 'COLOR_YUV420SP2BGRA', 'COLOR_YUV420SP2GRAY', 'COLOR_YUV420SP2RGB', 'COLOR_YUV420SP2RGBA', 'COLOR_YUV420p2BGR', 'COLOR_YUV420p2BGRA', 'COLOR_YUV420p2GRAY', 'COLOR_YUV420p2RGB', 'COLOR_YUV420p2RGBA', 'COLOR_YUV420sp2BGR', 'COLOR_YUV420sp2BGRA', 'COLOR_YUV420sp2GRAY', 'COLOR_YUV420sp2RGB', 'COLOR_YUV420sp2RGBA', 'COLOR_mRGBA2RGBA'] 04_image_color_split.py import cv2 img = cv2.imread('./images/input.jpg', cv2.IMREAD_COLOR) gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) yuv_img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV) y,u,v = cv2.split(yuv_img) cv2.imshow('Grayscale image', gray_img) cv2.imshow('Y channel', y) cv2.imshow('U channel', u) cv2.imshow('V channel', v) cv2.waitKey() 合并图像色带 05_image_color_merge.py import cv2 img = cv2.imread('./images/input.jpg', cv2.IMREAD_COLOR) g,b,r = cv2.split(img) gbr_img = cv2.merge((g,b,r)) rbr_img = cv2.merge((r,b,r)) cv2.imshow('Original', img) cv2.imshow('GRB', gbr_img) cv2.imshow('RBR', rbr_img) cv2.waitKey() 移动translation 06_image_translation.py import cv2 import numpy as np img = cv2.imread('images/input.jpg') num_rows, num_cols = img.shape[:2] translation_matrix = np.float32([ [1,0,70], [0,1,110] ]) img_translation = cv2.warpAffine(img, translation_matrix, (num_cols + 70, num_rows + 110)) translation_matrix = np.float32([ [1,0,-30], [0,1,-50] ]) img_translation = cv2.warpAffine(img_translation, translation_matrix, (num_cols + 70 + 30, num_rows + 110 + 50)) cv2.imshow('Translation', img_translation) cv2.waitKey() 旋转 07_image_rotation.py import cv2 import numpy as np img = cv2.imread('images/input.jpg') num_rows, num_cols = img.shape[:2] translation_matrix = np.float32([ [1,0,70], [0,1,110] ]) img_translation = cv2.warpAffine(img, translation_matrix, (num_cols + 70, num_rows + 110)) translation_matrix = np.float32([ [1,0,-30], [0,1,-50] ]) img_translation = cv2.warpAffine(img_translation, translation_matrix, (num_cols + 70 + 30, num_rows + 110 + 50)) cv2.imshow('Translation', img_translation) cv2.waitKey() 缩放 08_image_scaling.py import cv2 img = cv2.imread('images/input.jpg') img_scaled = cv2.resize(img,None,fx=1.2, fy=1.2, interpolation = cv2.INTER_LINEAR) cv2.imshow('Scaling - Linear Interpolation', img_scaled) img_scaled = cv2.resize(img,None,fx=1.2, fy=1.2, interpolation = cv2.INTER_CUBIC) cv2.imshow('Scaling - Cubic Interpolation', img_scaled) img_scaled = cv2.resize(img,(450, 400), interpolation = cv2.INTER_AREA) cv2.imshow('Scaling - Skewed Size', img_scaled) cv2.waitKey() 仿射变换 09_affine_transformation.py import cv2 import numpy as np img = cv2.imread('images/input.jpg') rows, cols = img.shape[:2] src_points = np.float32([[0,0], [cols-1,0], [0,rows-1]]) dst_points = np.float32([[0,0], [int(0.6*(cols-1)),0], [int(0.4*(cols-1)),rows-1]]) affine_matrix = cv2.getAffineTransform(src_points, dst_points) img_output = cv2.warpAffine(img, affine_matrix, (cols,rows)) cv2.imshow('Input', img) cv2.imshow('Output', img_output) cv2.waitKey() 射影变换 10_projective_transformation.py import cv2 import numpy as np img = cv2.imread('images/input.jpg') rows, cols = img.shape[:2] src_points = np.float32([[0,0], [cols-1,0], [0,rows-1], [cols-1,rows-1]]) dst_points = np.float32([[0,0], [cols-1,0], [int(0.33*cols),rows-1], [int(0.66*cols),rows-1]]) projective_matrix = cv2.getPerspectiveTransform(src_points, dst_points) img_output = cv2.warpPerspective(img, projective_matrix, (cols,rows)) cv2.imshow('Input', img) cv2.imshow('Output', img_output) cv2.waitKey() 图像变形 11_image_warping.py import numpy as np import math img = cv2.imread('images/input.jpg', cv2.IMREAD_GRAYSCALE) rows, cols = img.shape ##################### # Vertical wave img_output = np.zeros(img.shape, dtype=img.dtype) for i in range(rows): for j in range(cols): offset_x = int(25.0 * math.sin(2 * 3.14 * i / 180)) offset_y = 0 if j+offset_x < rows: img_output[i,j] = img[i,(j+offset_x)%cols] else: img_output[i,j] = 0 cv2.imshow('Input', img) cv2.imshow('Vertical wave', img_output) ##################### # Horizontal wave img_output = np.zeros(img.shape, dtype=img.dtype) for i in range(rows): for j in range(cols): offset_x = 0 offset_y = int(16.0 * math.sin(2 * 3.14 * j / 150)) if i+offset_y < rows: img_output[i,j] = img[(i+offset_y)%rows,j] else: img_output[i,j] = 0 cv2.imshow('Horizontal wave', img_output) ##################### # Both horizontal and vertical img_output = np.zeros(img.shape, dtype=img.dtype) for i in range(rows): for j in range(cols): offset_x = int(20.0 * math.sin(2 * 3.14 * i / 150)) offset_y = int(20.0 * math.cos(2 * 3.14 * j / 150)) if i+offset_y < rows and j+offset_x < cols: img_output[i,j] = img[(i+offset_y)%rows,(j+offset_x)%cols] else: img_output[i,j] = 0 cv2.imshow('Multidirectional wave', img_output) ##################### # Concave effect img_output = np.zeros(img.shape, dtype=img.dtype) for i in range(rows): for j in range(cols): offset_x = int(128.0 * math.sin(2 * 3.14 * i / (2*cols))) offset_y = 0 if j+offset_x < cols: img_output[i,j] = img[i,(j+offset_x)%cols] else: img_output[i,j] = 0 cv2.imshow('Concave', img_output) cv2.waitKey() 参考资料 讨论qq群144081101 591302926 567351477 钉钉免费群21745728 本文最新版本地址 本文涉及的python测试开发库 谢谢点赞! 本文相关海量书籍下载

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册