awesome py_skills

awesome py_skills

id()函数:获取对象的内存地址
str.replace()函数:替换字符
index(value)函数:在数据中查找第一次value的位置
str.rpartition(" ") 函数:以最右边的空格把字符串分为3部分
isinstance(1.3, (float, int))  # 只要是其中一个的实例就返回 True

#format方式  https://www.cnblogs.com/songdanlee/p/11105807.html
print('{:.4f}ms'.format(100000.125445)) # 保留4位小数  100000.1254ms
# *^20s 内容居中对齐,不够用*填充
print('{:*^20s} '.format("dorra")) # *******dorra********

#str 的 startswith 和 endswith 两个函数的参数可以是元组
str.endswith(('.jpg', '.gif'))

def py_switch(x): #实现switch-case语句
    return  switch_dict.get(x, None)

switch_dict = {"files":10, "folders":5, "devices":2}
print(py_switch("devices"))


numbers = [1, 2, 3, 4, 5] #star expression
one, *_, five = numbers
print(one, five) # 1 5

#str.format()
print ('{name} is {age} old.'.format(name = 'lee', age = 22))

# 文件名按数字升序排列
imgs = os.listdir("C:/Users/F7687778/Desktop/jpg_dir")
imgs.sort( key= lambda x: int(x.split(".")[0]) )
import uuid
user_id = uuid.uuid4()
print(user_id) # e42bd8e3-e2a7-4d32-b751-450e3babe130

import heapq
nums = [10,6,8,3,1] # 获取最大几个,最小几个
print(heapq.nlargest(1, nums)) # [10]
print(heapq.nlargest(3, nums)) # [10, 8, 6]

countr = {}
bag = ["a", "a", "a", "b", "b"]
for i in bag:
 countr[i] = countr.get(i, 0) + 1

print(countr) #{'a': 3, 'b': 2}

list(enumerate('ABC')) # [(0, 'A'), (1, 'B'), (2, 'C')]
list(enumerate('ABC', 1)) # [(1, 'A'), (2, 'B'), (3, 'C')]

expr = "[1, 2, 3]"
my_list = eval(expr)
print(my_list, type(my_list)) # [1, 2, 3] <class 'list'>

a = "{1: 'a', 2: 'b'}" # 字典字符串转字典
b = eval(a) # {1: 'a', 2: 'b'}


x, y = 50, 25
small = x if x < y else y  # 三元运算

#使用级联比较x < y < z
x, y, z = 1,2,3
if x < y < z:
    print("pass")

res = map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # Python 3.x 返回迭代器
print(list(res)) #[1, 4, 9, 16, 25]

#用lambda配合filter过滤
lst = ["rose", "jack", "snow", "lemon"]
f = filter(lambda x:x.startswith("rose"), lst)
print(list(f))

keys = ["a", "b", "c"]
vals = [1, 2, 3]
zipped = dict(zip(keys, vals)) 
print(zipped) # {'a': 1, 'b': 2, 'c': 3}


from collections import OrderedDict, Counter
# remembers the order the keys are added
dic = OrderedDict(a=1, b=2, c=3)
print(dic) # OrderedDict([('a', 1), ('b', 2), ('c', 3)])

# counts the frequency of each character
y = Counter("Hello")
print(y) # Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})

#找出列表中最常见的值
a = ["a", "a","a","b","b", "c"]
from collections import Counter
cnt = Counter(a)
print(cnt.most_common(1)) #[('a', 3)]
print(cnt.most_common(1)[0][0]) # a

x = [True, True, False]
if any(x):
    print("at least one true")

if all(x):
    print("all true")

if any(x) and not all(x):
    print("at least one true and one False")
# -*- coding:utf-8 -*-
class Person():
    # defining construction methods
    def __init__(self, name, grade, height):
        self.name = name
        self.grade = grade
        self.height = height

    def __str__(self):
        return '(%s, %d, %d)' % (self.name, self.grade, self.height)

p1 = Person('runoob', 5, 180)
p2 = Person('jack', 6, 170)
p3 = Person('coco', 5, 130)
p4 = Person('rose', 1, 120)

#一个学校的人站成一行,需要年级从小到大,并且每个年级里从矮到高
lis = [p1, p2, p3, p4]
print(lis[0], lis[1], lis[2], lis[3])
#(runoob, 5, 180) (jack, 6, 170) (coco, 5, 130) (rose, 1, 120)

lis.sort(key=lambda x: (x.grade, x.height))
print(lis[0], lis[1], lis[2], lis[3])
#(rose, 1, 120) (coco, 5, 130) (runoob, 5, 180) (jack, 6, 170)


#还是排序,我们希望把正的放前面,负的放后面,并且分别按绝对值从小到大
lst_l = [1, -2, 10, -12, -4, -5, 9, 2]
lst_l.sort(key=lambda x: (x < 0, abs(x)))
print(lst_l)

d = {"p1":2, "p2":3, "p3":0} #按值对dict排序
print(sorted(d.items(), key=lambda x:x[1])) # 方法1

from operator import itemgetter #itemgetter 替代 lambda
print(sorted(d.items(), key=itemgetter(1))) # 方法2


from itertools import chain
def flat_map(f, items): #扁平版本的 map
    return chain.from_iterable(map(f, items))

print(list(flat_map(list, ['123', '456'])))
#['1', '2', '3', '4', '5', '6']
# -*- coding:utf-8 -*-
import time
from functools import wraps

def timer(fn):
    @wraps(fn)
    def wrapper(*args, **kw):
        start = time.time()
        ret = fn(*args, **kw)
        # {:*^20s} ^ 内容居中  *^20s 内容居中对齐,不够用*填充  {:.4f} 保留4位小数
        print('The function {:*^20s}  run cost {:.4f} s'.format(fn.__name__, time.time()-start))
        return ret
    return wrapper


@timer
def test():
    s = 0
    for i in range(1,10001):
        s = s + i

    return s

if __name__ == '__main__':
    rs = test()
    print(rs)
    
    '''run result
    The function ********test********  run cost 0.0020 s
    50005000
    '''

用line_profiler性能调试工具检测每一行python代码的运行时间

#import wrapt  # utils.py
from functools import wraps  # utils.py
from line_profiler import LineProfiler
lp = LineProfiler()

#https://my.oschina.net/readerror/blog/2054612
def lp_wrapper(fn): #显示函数调用时间
    @wraps(fn)
    def wrapper(*args, **kwargs):
        global lp
        lp_wrapper = lp(fn)
        res = lp_wrapper(*args, **kwargs)
        lp.print_stats()
        return res

    return wrapper

@lp_wrapper
def func():
    a = sum([1, 2, 3])
    b = sum([1, 2, 3])
    return sum([a, b])

if __name__ == '__main__':
    func()
import cv2
from  PIL import  Image
import numpy as np


# 图片 大小是24*24 比较小, resize 224*224 放在神经网络里训练建模 再对视频流里面的crop (24*24) 进行
# 预测结果会有差异, 把crop save 再imread 就没有问题 原因分析

# cv2 读 存 差异对比
img_path = "C:/Users/F7687778/Desktop/ttt/213res_1.jpg"
cv2_img = cv2.imread(img_path)
cv2.imwrite("C:/Users/F7687778/Desktop/ttt/213res_2.jpg",
                       cv2_img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
cv2_img2 = cv2.imread("C:/Users/F7687778/Desktop/ttt/213res_2.jpg" )
res = cv2_img - cv2_img2
print(res.sum()) # 47522   说明前后2张图片不一样

# Image 读 存 差异对比
image = Image.open(img_path)
img=np.array(image)
image.save("C:/Users/F7687778/Desktop/ttt/213res_3.jpg", quality=100)
image2 = Image.open("C:/Users/F7687778/Desktop/ttt/213res_3.jpg")
img2=np.array(image2)
res2 = img - img2
print(res2.sum()) # 47522    说明前后2张图片不一样

# cv2 读 存bmp无损 差异对比
cv2_img2 = cv2.imread(img_path)
cv2.imwrite("C:/Users/F7687778/Desktop/ttt/213res_2.bmp", cv2_img2)
cv2_bmp = cv2.imread("C:/Users/F7687778/Desktop/ttt/213res_2.bmp")

res3 = cv2_img2 - cv2_bmp
print(res3.sum()) # 0   说明保存成 bmp格式的图片和之前的图片是一样的

# 结论 针对小图片 应该进行bmp 无损save, 然后 再拿save的图片AI建模,
# 再对视频流crop进行判断就没有问题了(无需 save 后再 读取)
# cv2 imwrite jpeg 图片会 去掉高频信息
# 有损压缩:无法分辨高频信息。于是可以把图片转换到某种频域,然后剔除高频信息,
# 只保留一定程度的低频信息。(傅立叶变换、小波变换、etc )
# -*- coding:utf-8 -*-
import cv2
import collections
import numpy as np

def getColorList():
    dict = collections.defaultdict(list)

    # black
    lower_black = np.array([0, 0, 0])
    upper_black = np.array([180, 255, 46])

    color_list = []
    color_list.append(lower_black)
    color_list.append(upper_black)
    dict['black'] = color_list

    # gray
    lower_gray = np.array([0, 0, 46])
    upper_gray = np.array([180, 43, 220])
    color_list = []
    color_list.append(lower_gray)
    color_list.append(upper_gray)
    dict['gray'] = color_list

    # red
    lower_red = np.array([156, 43, 46])
    upper_red = np.array([180, 255, 255])
    color_list = []
    color_list.append(lower_red)
    color_list.append(upper_red)
    dict['red'] = color_list

    return dict


image = cv2.imread('C:/Users/~/Desktop/dg.jpg')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

color_dict = getColorList()
mask_black_th = cv2.inRange(hsv, color_dict['black'][0], color_dict['black'][1])
mask_red_th = cv2.inRange(hsv, color_dict['red'][0], color_dict['red'][1])

#he_or = mask_black_th | mask_red_th  # 2张 二值化图片做或运算
he_or = cv2.bitwise_or(mask_black_th, mask_red_th) # 等效上面一句

#he_and = mask_black_th & mask_red_th  # 2张 二值化图片做与运算
#he_and = cv2.bitwise_and(mask_black_th, mask_red_th)  # 等效上面一句
cv2.imshow("mask_black_th", mask_black_th)
cv2.waitKey(5000)

cv2.imshow("mask_red_th", mask_red_th)
cv2.waitKey(5000)

cv2.imshow("he_or ", he_or )
cv2.waitKey(50000)

在这里插入图片描述

https://zhuanlan.zhihu.com/p/94382243
https://zhuanlan.zhihu.com/p/25892022
https://zhuanlan.zhihu.com/p/65968462
https://zhuanlan.zhihu.com/p/96657195

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值