记录一些Python的代码

openCV Code

cv2 v.s. PIL

特性cv2PIL
打开图像cv2.imread(‘test.jpg’)Image.open(‘test.jpg’)
图像模式BGRRGB
图像尺寸h, w, c = image.shapew, h = image.size
缩放im =cv2.resize(img2,(h,w)) 或者
im =cv2.resize(img2,None,fx,fy) fx,fy是缩放因子
im = img1.resize((w,h))
保存cv2.imwrite(path,img)img1.save(path)
转NumPy无需转换image = np.array(image,dtype=np.float32) # 默认是uint8
维度变成(h,w,c)了 注意ndarray中是 行row x 列col x 维度dim 所以行数是高,列数是宽
获取像素img[h,w,c]im.getpixel((w,h))
说明应该是先高后宽总是先宽后高

参考:
OpenCV、Skimage、PIL图像处理的细节差异
PIL:Image 和 cv2简单比较

cv2.resize(img, (0, 0), fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC) 
cv2.resize(img, None, None, fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC) 

imwrite 保存图片

imwrite(filename, img[, params])

params参数可选:

  • 对JPG而言, 其表示的是图像的质量,用0-100的整数表示,默认为95.
  • 对PNG而言, 其表示的是压缩级别, 从0到9, 压缩级别越高, 图像尺寸越小. 默认级别为3.

保存成PNG得到的图像质量更高,推荐保存成PNG

cv2.imwrite("./cat.jpg", img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])   
cv2.imwrite("./cat.png", img, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])  

caffe前向过程

# test for MobileNet
import numpy as np
import cv2
import caffe

MODEL_FILE = './V2/mobilenet_deploy.prototxt'
PRETRAIN_FILE = r'./V2/MNext_iter_6000.caffemodel'
caffe.set_mode_cpu()
net = caffe.Net(MODEL_FILE, PRETRAIN_FILE, caffe.TEST)

mean_vec = np.array([103.94, 116.78, 123.68], dtype=np.float32)
reshaped_mean_vec = mean_vec.reshape(1, 1, 3)

im = cv2.imread(impath)
im = cv2.resize(im, (160, 120))
im = im[60-56:60+56, 80-56:80+56, ...]
im = im - reshaped_mean_vec
im *= 0.017
im = im.transpose((2, 0, 1))
im_ = np.zeros((1, 3, 112, 112), dtype=np.float32)
im_[0, ...] = im

starttime = datetime.datetime.now()
predictions = net.forward(data=im_)
endtime = datetime.datetime.now()
print((endtime.microsecond - starttime.microsecond)/1000, "ms")

pred = predictions['prob']
print(pred.argmax())

caffe 自带的图像预处理

transformer.set_transpose('data', (2,0,1))    #改变维度的顺序,由原始图片(28,28,3)变为(3,28,28)
#transformer.set_mean('data', np.load(mean_file).mean(1).mean(1))    #减去均值,前面训练模型时没有减均值,这儿就不用
transformer.set_raw_scale('data', 255)    # 缩放到【0,255】之间
transformer.set_channel_swap('data', (2,1,0))   #交换通道,将图片由RGB变为BGR

参考 denny的学习专栏
#NumPy Code

标量函数向量化

import numpy as np
from numpy import vectorize

def r_lookup(x):
    return x + 1
 
r_lookup_vec = vectorize(r_lookup)
a = np.arange(28*28).reshape(28, 28)
b = r_lookup_vec(a)

numpy中axis

在numpy中,.sum(axis=n)解释:
如果,b是一个shap(5, 6, 7, 8)的numpy array, 然后,c = b.sum(axis=2)
那么,c的shape将是(5, 6, 8) ,因为“7”就是axis=2,被清除了。而且,c[x, y, z] = sum( b[x, y, : , z])
from

If you do .sum(axis=n), for example, then dimension n is collapsed and deleted, with all values in the new matrix equal to the sum of the corresponding collapsed values. For example, if b has shape (5,6,7,8), and you do c = b.sum(axis=2), then axis 2 (dimension with size 7) is collapsed, and the result has shape (5,6,8). Furthermore, c[x,y,z] is equal to the sum of all elements c[x,y,:,z].


numpy.unravel_index

给定一个矩阵,求第n个元素在shape下的下标是什么?矩阵各维的下标从0开始

例如:

print np.unravel_index(100, (6, 7, 8))
(1, 5, 4)

解释:
给定一个矩阵,shape=(6, 7, 8),即3维的矩阵,求第100个元素的下标。

 a = np.arange(15).reshape(3,5)
 maxidx = a.argmax()   # 最大值的一维位置, 结果为14
 np.unravel_index(maxidx, a.shape)  # 最大值在a.shape下的位置,结果为(2,4)

where

类似于matlab中的find函数

idx = np.where((x > 1) | (x < 0))
dx[idx] = -dx[idx]

常用函数

# -*- coding: utf-8 -*-
'''
保存经常用到的python 函数
'''
import os
import shutil
import random


def list_op():
    list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    random.shuffle(list)   # 打乱列表
    slice = random.sample(list, 5)  # 从list中随机获取5个元素,作为一个片断返回
    return slice
    pass


def str2():
    # 字符串转为元组,返回:(1, 2, 3)
    print tuple(eval("(1,2,3)"))
    # 字符串转为列表,返回:[1, 2, 3]
    print list(eval("(1,2,3)"))
    # 字符串转为字典,返回:<type 'dict'>
    print type(eval("{'name':'ljq', 'age':24}"))


def genMatrix(rows, cols):
    matrix = [[0 for col in range(cols)] for row in range(rows)]
    return matrix


def PNG2JPG():
    from PIL import Image
    img = Image.open("D:\\1.png")
    img.save("1.jpeg", format="jpeg")


# 文件操作
def FileOP():
    # 目录操作:
    os.mkdir("file")
    # 创建目录
    # 复制文件:
    shutil.copyfile("oldfile", "newfile")  # oldfile和newfile都只能是文件
    shutil.copy("oldfile", "newfile")   # oldfile只能是文件夹,newfile可以是文件,也可以是目标目录

    # 复制文件夹:
    shutil.copytree("olddir", "newdir")  # olddir和newdir都只能是目录,且newdir必须不存在
    # 重命名文件(目录)
    os.rename("oldname", "newname")
    # 文件或目录都是使用这条命令
    # 移动文件(目录)
    shutil.move("oldpos", "newpos")
    # 删除文件
    os.remove("file")
    # 删除目录
    os.rmdir("dir")
    # 只能删除空目录
    shutil.rmtree("dir")
    # 空目录、有内容的目录都可以删
    # 转换目录
    os.chdir("path")
    # 换路径


def FunOP():
    l = [1, 3, 5, 6, 7, 8]
    b = map(lambda a, b: [a, b], l[::2], l[1::2])  # b = [[1,3],[5,6],[7,8]]
    return b
    pass


def getAllLabelTxt(root_path):
    os.system('dir ' + root_path + '\\*.txt /b/s> file_list.txt')
    txt = open('file_list.txt', 'r').readlines()
    # os.remove('file_list.txt')
    return txt

	
def saveList(man):
	try:
		man_file=open('man.txt', 'w')      # 以w模式访问文件man.txt
		other_file=open('other.txt','w')   # 以w模式访问文件other.txt
		print (man, file=man_file)         # 将列表man的内容写到文件中
		print (other, file=other_file)
	except IOError:
		print ('File error')
	finally:
		man_file.close()
		other_file.close()

python版本控制

import sys
if sys.version_info < (3, 4):
    raise RuntimeError('At least Python 3.4 is required')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值