计算机视觉前置知识-Python基础

各位美女帅哥,如你所见,这篇文章是计算机视觉的前置基础知识。今年是2024年,计算机视觉包括计算机图形学领域科研的主流工具是Pytorch。耐心看完你就掌握了计算机视觉所需要的Python基础了!这个章节我是按照官网的知识结构写的,但不是完全翻译搬运,有纰漏的话,please feel free to tell me!

先看看目录,有一个框架:

目录

1.1 Python Version - Python 版本

1.2 Basic Data Types - 基本数据类型

1.2.1 Integers(整型)和 floats(浮点数)

1.2.2 Booleans(布尔值)

1.2.3 Strings(字符串)

1.3 Containers(容器)

1.3.1 Lists(列表)

List 创建&定义

List 操作

(1)List Slicing(列表切片)

(2)List Loops(列表循环)

(3)List comprehensions(列表推导)

1.3.2 Dictionaries(字典)

Dictionary 创建&定义

 Dictionary 操作

(1)Dictionary Loop(字典循环)

(2)Dictionary comprehensions(字典推导)

1.3.3 Sets(集合)

Dictionary 创建&定义

 Dictionary 操作

(1)Set Loop(集合循环)

(2)Set comprehensions(集合推导)

1.3.4 Tuples(元组)

1.3.5 回顾

1.4 Functions(函数)

1.5 Classes(类)

1.1 Python Version - Python 版本

官方课程代码推荐使用Jupyter notebook,或者Colab,下面的代码可以粘上去run一下。

Python版本: >=3.7(命令行输入python --version查看自己的Python版本)

1.2 Basic Data Types - 基本数据类型

Python的数据类型和其它编程语言很相似,基本数据类型包括 integers(整型), floats(浮点数), booleans(布尔值), 以及 strings(字符串)

1.2.1 Integers(整型)和 floats(浮点数)

和其它编程语言的区别不大,简单理解成整数和小数吧!注意在Python里没有 x++ 和 x-- 这两个运算:

x = 3
print(type(x)) # Prints "<class 'int'>"
print(x)       # Prints "3"
print(x + 1)   # Addition; prints "4"
print(x - 1)   # Subtraction; prints "2"
print(x * 2)   # Multiplication; prints "6"
print(x ** 2)  # Exponentiation; prints "9"
x += 1
print(x)  # Prints "4"
x *= 2
print(x)  # Prints "8"
y = 2.5
print(type(y)) # Prints "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"

1.2.2 Booleans(布尔值)

“True”还是“False”,是或否?Python 用英语表示,而不像其它编程语言用符号表示,但是它们的用法大致相同:

t = True
f = False
print(type(t)) # Prints "<class 'bool'>"
print(t and f) # Logical AND; prints "False"
print(t or f)  # Logical OR; prints "True"
print(not t)   # Logical NOT; prints "False"
print(t != f)  # Logical XOR; prints "True"

1.2.3 Strings(字符串)

Python 的字符串功能有种随心所欲的强大:

hello = 'hello'    # String literals can use single quotes
world = "world"    # or double quotes; it does not matter.
print(hello)       # Prints "hello"
print(len(hello))  # String length; prints "5"
hw = hello + ' ' + world  # String concatenation
print(hw)  # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting
print(hw12)  # prints "hello world 12"

还有很多 methods,更多功能在这份文档里(全英文警告)Built-in Types — Python 3.5.9 documentation

s = "hello"
print(s.capitalize())  # Capitalize a string; prints "Hello"
print(s.upper())       # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7))      # Right-justify a string, padding with spaces; prints "  hello"
print(s.center(7))     # Center a string, padding with spaces; prints " hello "
print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another;
                                # prints "he(ell)(ell)o"
print('  world '.strip())  # Strip leading and trailing whitespace; prints "world"

1.3 Containers(容器)

Python 有一些天生自带容器类型包括 lists(列表), dictionaries(字典), sets(集合), 和 tuples(元组)。

1.3.1 Lists(列表)

  • List 创建&定义

这里有必要区分一下 Python 中的 list 和 array,不刻意区分容易搞混:

List(列表)Array(数组)
是否调用库否,Python自带需调用Numpy库
数据类型存储任意类型的有序元素序列。所有元素必须是同一类型,如全是整数或全是浮点数。
存储灵活性动态,可以存储任何类型的数据必须是固定类型,通常用于存储数值数据
操作灵活性支持通用操作,如插入、删除、排序等。支持很多专门用于数值计算的操作(如矩阵运算、线性代数操作等)
速度和内存通用的数据结构,数值计算方面性能不如高效。内存效率比 list 高,并且在数值计算方面的速度通常更快。
应用场景适用于存储和处理各种类型的混合数据适合数值计算,特别是在大规模科学计算中

List 示例:

my_list = [1, "apple", 3.14, [1, 2, 3]]  # 包含整数、字符串、浮点数和子列表的列表
print(my_list)  # 输出: [1, 'apple', 3.14, [1, 2, 3]]

Array 示例:

import numpy as np

my_array = np.array([1, 2, 3, 4])  # 创建一个包含整数的数组
print(my_array)  # 输出: [1 2 3 4]
print(my_array + 2)  # 数组加法:输出 [3 4 5 6]
  • List 操作
(1)List Slicing(列表切片)

访问 list 中的元素和子列表

nums = list(range(5))     # range is a built-in function that creates a list of integers
print(nums)               # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4])          # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])           # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])           # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])            # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[:-1])          # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9]        # Assign a new sublist to a slice
print(nums)               # Prints "[0, 1, 8, 9, 4]"
(2)List Loops(列表循环)
animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print(animal)
# Prints "cat", "dog", "monkey", each on its own line.

 如果你想访问循环体中每个元素的索引,使用内置的 enumerate(枚举)函数:

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
(3)List comprehensions(列表推导)

有时候我们想将一种数据类型转换成另一种数据类型。在这个例子中,将 nums 列表中的每个元素通过平方运算 x ** 2 转换为新值,并生成一个包含这些新值的新列表 squares

nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares)   # Prints [0, 1, 4, 9, 16]

甚至可以加入条件语句:

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)  # Prints "[0, 4, 16]"

1.3.2 Dictionaries(字典)

  • Dictionary 创建&定义

字典存储(Key、Value)键值对:

d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
print(d['cat'])       # Get an entry from a dictionary; prints "cute"
print('cat' in d)     # Check if a dictionary has a given key; prints "True"
d['fish'] = 'wet'     # Set an entry in a dictionary
print(d['fish'])      # Prints "wet"
# print(d['monkey'])  # KeyError: 'monkey' not a key of d
# 使用.get安全访问,如果访问的key不存在,不报错而是输出"N/A",使程序不会中断
print(d.get('monkey', 'N/A'))  # Get an element with a default; prints "N/A"
print(d.get('fish', 'N/A'))    # Get an element with a default; prints "wet"
del d['fish']         # Remove an element from a dictionary
print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"
  •  Dictionary 操作
(1)Dictionary Loop(字典循环)
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
    legs = d[animal]
    print('A %s has %d legs' % (animal, legs))
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"

 如果你想访问 key 和它对应的 value,使用 items 方法:

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
    print('A %s has %d legs' % (animal, legs))
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"
(2)Dictionary comprehensions(字典推导)
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square)  # Prints "{0: 0, 2: 4, 4: 16}"

1.3.3 Sets(集合)

Dictionary 创建&定义

set 是不同元素的无序集合:

animals = {'cat', 'dog'}
print('cat' in animals)   # Check if an element is in a set; prints "True"
print('fish' in animals)  # prints "False"
animals.add('fish')       # Add an element to a set
print('fish' in animals)  # Prints "True"
print(len(animals))       # Number of elements in a set; prints "3"
animals.add('cat')        # Adding an element that is already in the set does nothing
print(len(animals))       # Prints "3"
animals.remove('cat')     # Remove an element from a set
print(len(animals))       # Prints "2"
 Dictionary 操作
(1)Set Loop(集合循环)
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))
# Prints "#1: fish", "#2: dog", "#3: cat"
(2)Set comprehensions(集合推导)

from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)  # Prints "{0, 1, 2, 3, 4, 5}"

1.3.4 Tuples(元组)

元组是一个(不可变的) list of values(值列表)。元组在很多方面类似于 list;最重要的区别之一是元组可以用作字典中的键和集合的元素,而列表则不能。

d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
t = (5, 6)        # Create a tuple
print(type(t))    # Prints "<class 'tuple'>"
print(d[t])       # Prints "5"
print(d[(1, 2)])  # Prints "1"

1.3.5 回顾

光看一遍都晕了,来对比看看它们的定义和创建:

# List 创建&定义:
my_list = [1, 2, 3, 4, 5] # 包含整数的列表
mixed_list = [1, "apple", 3.14] # 混合类型的列表
empty_list = [] # 创建空列表

# Dictionary 创建&定义
my_dict = {'cat': 'cute', 'dog': 'furry'}
empty_dict = {}  # 创建空字典

# Set 创建&定义
my_set = {1, 2, 3, 4}
empty_set = set()  # 创建空集合

# Tuple 创建&定义
my_tuple = (1, 2, 3)
single_element_tuple = (5,)  # 单个元素的元组需要加逗号
empty_tuple = ()  # 创建空元组

你学废了吗?

1.4 Functions(函数)

Python函数是使用 def 关键字定义的:

def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'

for x in [-1, 0, 1]:
    print(sign(x))
# Prints "negative", "zero", "positive"

 我们经常将函数定义为接受可选关键字参数:

def hello(name, loud=False):
    if loud:
        print('HELLO, %s!' % name.upper())
    else:
        print('Hello, %s' % name)

hello('Bob') # Prints "Hello, Bob"
hello('Fred', loud=True)  # Prints "HELLO, FRED!"

可选参数:如果调用时不传递参数 loud,默认使用 False

有什么用:根据 loud 的值,函数可以有不同的执行路径。

1.5 Classes(类)

如果没有基础,要专门学一下 class(类)这个东西(挖个坑以后填上)。Python官方 class 文档在此(全英文警告):Classes — Python 3.5.9 documentation

class Greeter(object):

    # Constructor
    def __init__(self, name):
        self.name = name  # Create an instance variable

    # Instance method
    def greet(self, loud=False):
        if loud:
            print('HELLO, %s!' % self.name.upper())
        else:
            print('Hello, %s' % self.name)

g = Greeter('Fred')  # Construct an instance of the Greeter class
g.greet()            # Call an instance method; prints "Hello, Fred"
g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"

你学废了吗?下一节我们学习Numpy。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值