python学习&CNN实例

python

一.环境配置

一.python环境配置安装

1.下载anaconda(库)
2.anaconda prompt
1)常用命令

  • conda list:查anaconda中现有的库。(库名+版本+安装方式)
  • pip install 包名:安装anaconda中还未有的库(以及包括库需要的依赖)。若装库遇到问题 此网站有python的外部包,ctrl+f搜寻,eg:xgboost‑1.3.1‑cp36‑cp36m‑win_amd64.whl:名称+版本+python版本+位数+whl(pip安装)。再用pip install安装。
  • conda install 与pip下载源可能不一样,建议pip。

3.jupyter-notebook(可以注释+可视化+代码+方便查看中间信息)

  • shift+enter:执行
  • import os
    print(os.path.abspath(’.’))显示当前路径,可新建文件夹然后将代码放进去。

4.安装opencv
1)pip install python-opencv
2)查看是否安装成功
python(环境名)
import cv2 (不报错即安装成功)
cv2.version(打印版本号)
exit()(退出)
同理,安装pip install opencv-contrib-python==(版本号与opencv一致):是opencv的扩展包

二.python操作

1.数值运算

  • notebook只打印最后一行;
  • 2 3 2^3 23:2**3
  • x=3(赋值操作);type(x):打印类型;类型转换:float(x);y=‘123’,int(y)(数值才能转换);
  • abs:绝对值;round:四舍五入;min;max;1.3e2=130:e2为10的幂数
  • a=True(bool类型)

2字符串操作

  • ‘x’+‘y’:字符串拼接; x=‘a’,x*3:三倍字符串的字符串;len(x):字符串长度(包括空格);
  • 分割:x=‘1,2,2’ x.split(’,’):以’,'为分隔符切割,不写默认空格切割,切割的东西放在list中;
  • 合并:x=‘a’,x.join(y):以x的字符串的方式合并y;
  • 替换:x.replace(‘a’,‘b’):把x中的a替换成b;
  • 大小写转换:x.upper();x.lower();
  • 去空格: x=’ sad sda ',x.strip():去x得前后空格;x.lstrip():左空格,同理有空格;
  • 传值:’{} {} {}’.format(‘a’,‘b’,‘c’) 输出:‘a b c’;按位置传值:’{2} {0} {1}’.format(‘a’,‘b’,‘c’) 输出:‘c a b’;按参数传值:’{a},{b} {c}’.format(a=1,b=4,c=3) 输出:‘1,4 3’
  • 传值方式2:
x='a'
b=123
c=2.67
result='%s,%d %f'%(x,b,c)
result

结果:‘a,123 2.670000’

3.索引

  • x为字符串,x[0],x[-1]:从后往前数从-1开始;数字表示位置,正数时从左到右从0开始,负数是从右到左从-1开始;
  • 切片:取中间 x[0:4]:取从0到4,左闭右开;x[5:]:从5位置往后都取;x[:7]:左边全要;x[:]:全要;x[::2]:每隔两个取一个值。

4.list(元组?)

  • list以[]来创建,里面不限类型,不限长度;x = [1,‘a’,56.0];
  • len(x);
  • a为list,b为list,a+b为拼接;a*3:复制三遍;a[0],a[-1]:索引;a[0] = 22:单个替换;a[:] = [‘a’,‘b’]:全部替换,注意个数;
  • list操作与索引操作基本一样;
  • 删除:del a[0]:注意:多次执行会改变内容;del a[3:]:删除3后面的所有;
  • 判断list是否有某元素:8 in a;3 not in a;同样也可以判断字符串;
  • list里面可以镶嵌list:多维数组;
  • 计数:a.count(计数内容);
  • 找某元素得索引:a.index(某元素);
  • 添加:a.append(需添加得元素):一次只能加一个;插入:a.insert(插入位置,插入元素);a.remove(被remove得元素):如果有多个,默认第一个;弹出:a.pop(弹出位置):返回弹出得元素,弹出以后,a里面被弹出得元素已经不存在;
  • 排序:a.sort():输出是排序后得结果,并且a中的元素已经被排序;若不想a发生变化,则b = sorted(a):a顺序未变,b内容被排序了;掉序:a.reverse():a的内容已经被掉序;

5.字典(key-value)

  • 字典用{}定义,字符串用’’,list用[];
  • 赋值:x[‘asd’]=594,key要唯一;a ={‘c’:1,‘b’:5}:字典之中无顺序:故只能用key去索引;
  • 取值:x[‘key’]:通过key找value;x.get(‘key’);x.get(‘key’,‘do not exist’):当查询的key值不存在时,输出后面的信息(无论什么)
  • 改:x[‘asd’]=345
  • 删:del x[‘key’]
  • 查:‘key’ in x
  • key一般为字符串,value可以为任意的类型
  • 弹出,x.pop(‘key’)与list一样
  • 更新:x1,x2为两个字典,x1.update(x2):将x1中没有,x2有的增加;x1有,x2有的更新
  • 打印所有的key:x.keys();打印所有的value:x.values();都打印:x.items()

6.集合(元素具有唯一性,一般用于去重)

  • 赋值:x = {1,23,4,4,4}会自动去掉重复
  • 并:a,b为集合,a.union(b)或者a|b
  • 交:a.intersection(b)或者a & b
  • 差:a.difference(b)或者a-b;b.dirrerence(a)=b-a;
  • 包含:b.issubset(a):b是否包含于a 或者 b<=a(子集),b<a (真子集)
  • 加:a.add(5)
  • 删:a.remove(5)
  • 更新:a.update([5,6,7])
  • 弹出:a.pop():集合无序,故不能加参数

7.赋值机制

  • x=10 y=x :则x、y指向同一个内存空间,查内存空间:id(x),判断内存空间是否相等:x is y
  • x=1000,y=1000:它们的内存空间不一样
  • x=1,y=1:在数值比较小的时候,x与y的内存空间可能一样

8.判断结构

  • 以缩进来控制结构
x = 0
if x<0:
    print('x<0')
elif x>0:
    print('x>0')
else:
    print('x=0')

9.循环结构

  • while
x = 5
while x<7:
    print(x)
    x+=1
x=['a','b',5]
while x:
    y=x.pop();
    print(y)
  • for
x={
    
    'a','b','c',5}
for y in x:
    print(y)
x='zhou er'
for i in range(len(x)):
    print(x[i])

range 相当于给出索引

x = [1,3,6,8]
for i in x:
    if i%2 == 0:
        print(i)
    else:
        continue
    print(i)

continue是后面的不执行了,直接进行下一次循环;
break是后面的不执行了,直接跳出此次循环。

10.函数

  • 括号里面的为默认值,若传参个数只有一个,默认是传的第一个
def add_op(a=1,b=4):
    return (a+b)
x = add_op(4,6)
  • 传参个数不确定(*x)
def add_op(a,*arg):
    for i in arg:
        a+=i
    return (a)    
add_op(1,9,0,4)
  • 传入不定个数的键值对(**xx)
def add_op(a,**kwargs):
    for key,value in kwargs.items():
        print(key,value)
add_op(6,d=1,b=5,c=9)
  • 返回多个值
def add_op(a,*arg):
    b=0
    for i in arg:
        a+=i
        b+=i
    return a,b   
a,b=add_op(1,9,0,4)
print(a,b)

11.模块与包

  • 写包
%%writefile qiu.py
a = 10
def b(c):
    sum = 0 
    for i in c:
        sum+=i
    return sum
c = [1,2,3,4,5]
print(b(c))
  • 导包
import qiu as q

导入一部分

from qiu import a,b

导入全部

from qiu import *
  • 运用包
q.a=1
c=[1,8,4]
q.b(c)
  • 删包
import os
os.remove('qiu.py')

12.异常处理

import math
for i in range(3):
    try:
        x = input("input a number")
        if x == 'q':
            break
        else:
            y = math.log(float(x))
            print(y)
    except:
        print("error")
  • except +异常名称:捕捉特定异常

  • except Exception:捕捉所有异常

  • 捕捉多个异常
    except 异常a:
       \space \space    操作
    except 异常b:
       \space \space    操作

  • 自定义异常(raise:抛出异常,try & except 捕捉)

class xerror (ValueError):
    pass
x_list=['a','b','c']
while True:
    x_input = input()
    if x_input not in x_list:
        raise xerror('xrror')
  • finally:如果不出现异常,则最后执行finally的操作,如果出现异常,执行finally的操作,即无论遇到异常与否否要执行finally,比如在读文件时,发生异常,finally要关闭文件,以免忘记
try:
    1/0
except:
    print('value error')
finally:
    print('op finished')

13.文件操作

  • 创建
%%writefile qiu.txt
a b c d e
  • 读:一般情况,代码与数据、图放在同一个路径下,新建一个文件夹放图和数据
txt = open('./data/qiu.txt') #“./”:当前文件夹,/=下?当前文件夹下data下qiu.txt文件
txt_read = txt.read()
print(txt_read)

  • 一行一行读
txt =open('./qiu.txt')
read_lines = txt.readlines() #结果的每一行都存在一个list中
print(read_lines)  #结果:['a b c d e\n', '4 5 6 7 8\n', 'q q\n'],其中\n为敲的回车键
for line in read_lines:
    print(line)
  • 关:txt.close()
  • 写:写完文件关闭文件后才能读文件
txt = open('qiu2','w') #'qiu2'为文件名 ‘w’为write,如果qiu2以前有东西,则W操作会把以前的内容覆盖
txt.write('1,2,3,4\n') #如果为‘a’:则为在qiu2后面追加
txt.write('a,b,c,d')
txt.close()
txt = open('qiu2','w')
try:
    for i in range(10):
        txt.write(str(i)+'\n')
        10/(i-5)
except:
    print("error:",i)
finally:
    txt.close()
with open('qiu2','w') as q:   #此方法与上面的方法异曲同工,好处在于自动关闭文件
    q.write('sda,sdad')

14.类

  • 定义:
class people :
    '帮助信息:x'
    #所有实例都会共享的
    number =10
    def __init__(self,name,age):  //构造函数 self为本类,不作为参数传
        self.name = name
        self. age = age
    def display_name(self):
        print(self.name)
    def display_age(self):
        print(self.age)
  • 使用
    1)people.__doc__:打印帮助信息等,内置属性
    2)创建:

p1 =people('aki',20)
p1.name #属性
p1.display_name()
p1.name='c'# 更改属性
del p1.name # 删除属性
p1.display_age()

3)其他:`

hasattr(p1,'name'):判断p1是否有name值
getattr(p1,'age') #得到p1的age属性
setattr(p1,'name','qiu') # 将p1的name属性设置成qiu
delattr(p1,'name') # 删除p1的name属性


print(people.__doc__)
print(people.__name__)
print(people.__module__)
print(people.__bases__) #父类信息
print(people.__dict__)
  • 继承 &方法重写(父类方法不适用)
class parent:
    number = 100
    def __init__(self):
        print('这是父类的构造函数')
    def parentM(self):
        print('这是父类的方法')
    def setAttr(self,attr):
        parent.parentAttr=attr
    def getAttr(self):
        print('父类属性:',parent.parentAttr)
    def newM(self):
        print('父类中需要被重写的方法')
        
class child(parent):
    def __init__(self):
        print('这是子类构造函数')
    def childM(self):
        print('这是子类方法')
    def newM(self):
        print('子类重写父类的方法')

调用:

c = child()
c.childM()
c.parentM()
c.setAttr(10)
c.getAttr()
c.newM()

结果:先调用子类的构造函数,但不会调用父类的构造函数,子类可以调用父类的方法属性等

这是子类构造函数
这是子类方法
这是父类的方法
父类属性: 10
子类重写父类的方法

15.时间操作

  • 时间戳与当前时间
import time #可以用时间戳的差异值计算程序运行时间
print(time.time()) #时间戳:显示的是从1970.1.1到现在的时间
print(time.localtime(time.time()))#当前时间

print(time.localtime())#显示当前时间 里面的time.time()写不写都可以
print(time.asctime(time.localtime(time.time())))#对当前时间格式化成不同的类型
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) ##按指定格式输出当前时间,用来画图
  • 日历
import calendar
print(calendar.month(2021,8)) #显示日历
print(help(calendar.month))  #查看帮助

CNN实例

一.图像基本操作

1.数据读取——图片

  • 每一张图片由pixel组成,彩色有3个隧道,黑白有一个隧道,每一个隧道的pixel值为亮度(0-255,0最暗)
  • 每张图片都为一个像素矩阵
  • cv2.IMREAD_COLOR:彩色图片
  • cv2.IMREAD_GRAYSCALE:灰度图片
import cv2 #opencv读取的格式为BGR
import matplotlib.pyplot as plt #matplotlib绘图展示
import numpy as np #最基本数值计算工具包
#只在notebook使用,展示方便,不用show
%matplotlib inline 

img = cv2.imread('dog.jpg') #img为三维像素矩阵

cv2.imshow('dog',img) #图片的显示,也可以创建多个窗口:窗口名称,被展示图品
cv2.waitKey(0) #等待时候,毫秒级,0为任意键关闭,若为10000,则展示10000毫秒
cv2.destroyAllWindows()
  • 做成一个函数,方便使用
#做成一个函数,方便使用
def cv_show(name,img):
    cv2.imshow(name,img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
  • 显示图片大小
img.shape #(hight,width,channel)
  • 转化为灰度图片
img = cv2.imread('dog.jpg',cv2.IMREAD_GRAYSCALE)
  • 保存图片(注意要写类型xx.jpg?)
cv2.imwrite('cat.jpg',img)
  • 其他
type(img) #结果:numpy.ndarray
img.size #结果:163014
img.dtype #结果:dtype('uint8')

2.数据读取——视频

cv = cv2.VideoCapture('./vedio/cat.mp4')
if cv.isOpened():
    open,frame = cv.read() #open为bool值,frame为读到的第一帧
else:
    open=False
while open:
    ret,frame = cv.read()
    if frame is None:
        break
    if ret == True:    ##读到了东西
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) #灰度处理
        cv2.imshow('result',gray)
        if cv2.waitKey(10)&0xFF == 27: #退出
            break
cv.release()
cv2.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/qq_16600319/article/details/119529308