[python]-opencv、numpy、matplotlib、pandas练习代码

#导入cv模块
import cv2 as cv
#读取图像,支持 bmp、jpg、png、tiff 等常用格式
img = cv.imread("test.png",cv.IMREAD_GRAYSCALE)
res=cv.resize(img,None,fx=50,fy=50,interpolation=cv.INTER_CUBIC)
#创建窗口并显示图像 
cv.namedWindow("YOUR MATHER")
cv.imshow("YOUR MATHER",res)
cv.waitKey(0)
#释放窗口
cv2.destroyAllWindows() 
import numpy as np
import cv2 as cv
img = cv.imread("test.png",0)
print(img)
# 获取某个像素点的值

rows,cols=img.shape

M=cv.getRotationMatrix2D(((cols-1)/2.0,(rows-1)/2.0),90,1)
print()
print(M)

# px = img[100,100]
# print(px)
# # 仅获取蓝色通道的强度值
# blue = img[100,100,0]
# print("blue:")
# print(blue)
# # 修改某个位置的像素值
# img[100,100] = [255,255,255]
# # cv.imshow("blue",blue)

# # cv.waitKey(0)
# #释放窗口
# # cv.destroyAllWindows() 

# M = np.float32([[1,0,100],[0,1,50]])
# print(M)
# dst = cv.warpAffine(img,M,(cols,rows))
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

# 1 读取图像
img1 = cv.imread("test2.png")
img2 = cv.imread("meinv2.png")

# 2 加法操作
img3 = cv.add(img1,img2) # cv中的加法
img4 = img1+img2 # 直接相加

# 3 图像显示
fig,axes=plt.subplots(nrows=1,ncols=2,figsize=(10,8),dpi=100)
axes[0].imshow(img3[:,:,::-1])
axes[0].set_title("cv中的加法")
axes[1].imshow(img4[:,:,::-1])
axes[1].set_title("直接相加")
plt.show()
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab

im=np.zeros((8,8),dtype=np.uint8)
im[0,3]=255
print(im)

pylab.gray()
pylab.imshow(im)



import numpy as np


arr = np.arange(49).reshape(3,4,4)
arr.resize()
print(arr)
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('test.png',0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic') 
plt.show()
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    # 逐帧捕获
    ret, frame = cap.read()
    # 如果正确读取帧,ret为True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # 我们在框架上的操作到这里
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # 显示结果帧e
    cv.imshow('frame', gray)
    if cv.waitKey(1) == ord('q'):
        break
# 完成所有操作后,释放捕获器
cap.release()
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
# 定义编解码器并创建VideoWriter对象
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi', fourcc, 20.0, (640,  480))
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    frame = cv.flip(frame, 0)
    # 写翻转的框架
    out.write(frame)
    cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break
# 完成工作后释放所有内容
cap.release()
out.release()
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
# 鼠标回调函数
def draw_circle(event,x,y,flags,param):
    if event == cv.EVENT_LBUTTONDBLCLK:
        cv.circle(img,(x,y),100,(255,0,0),-1)
# 创建一个黑色的图像,一个窗口,并绑定到窗口的功能
img = np.zeros((512,512,3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_circle)
while(1):
    cv.imshow('image',img)
    if cv.waitKey(20) & 0xFF == 27:
        break
cv.destroyAllWindows()
import cv2 as cv
events = [i for i in dir(cv) if 'EVENT' in i]
print( events )
import numpy as np
import cv2 as cv
def nothing(x):
    pass
# 创建一个黑色的图像,一个窗口
img = np.zeros((300,512,3), np.uint8)
cv.namedWindow('image')
# 创建颜色变化的轨迹栏
cv.createTrackbar('R','image',0,255,nothing)
cv.createTrackbar('G','image',0,255,nothing)
cv.createTrackbar('B','image',0,255,nothing)
# 为 ON/OFF 功能创建开关
switch = '0 : OFF \n1 : ON'
cv.createTrackbar(switch, 'image',0,1,nothing)
while(1):
    cv.imshow('image',img)
    k = cv.waitKey(1) & 0xFF
    if k == 27:
        break
    # 得到四条轨迹的当前位置
    r = cv.getTrackbarPos('R','image')
    g = cv.getTrackbarPos('G','image')
    b = cv.getTrackbarPos('B','image')
    s = cv.getTrackbarPos(switch,'image')
    if s == 0:
        img[:] = 0
    else:
        img[:] = [b,g,r]
cv.destroyAllWindows()
import cv2 as cv
flags = [i for i in dir(cv) if i.startswith('COLOR_')]
print( flags )
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('test.png',0)
ret,thresh1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
ret,thresh2 = cv.threshold(img,127,255,cv.THRESH_BINARY_INV)
ret,thresh3 = cv.threshold(img,127,255,cv.THRESH_TRUNC)
ret,thresh4 = cv.threshold(img,127,255,cv.THRESH_TOZERO)
ret,thresh5 = cv.threshold(img,127,255,cv.THRESH_TOZERO_INV)
titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in range(6):
    plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('test.png',0)
# 全局阈值
ret1,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
# Otsu阈值
ret2,th2 = cv.threshold(img,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)
print(th2)
# 高斯滤波后再采用Otsu阈值
blur = cv.GaussianBlur(img,(5,5),0)
ret3,th3 = cv.threshold(blur,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)
# 绘制所有图像及其直方图
images = [img, 0, th1,
          img, 0, th2,
          blur, 0, th3]
titles = ['Original Noisy Image','Histogram','Global Thresholding (v=127)',
          'Original Noisy Image','Histogram',"Otsu's Thresholding",
          'Gaussian filtered Image','Histogram',"Otsu's Thresholding"]
for i in range(3):
    plt.subplot(3,3,i*3+1),plt.imshow(images[i*3],'gray')
    plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
    plt.subplot(3,3,i*3+2),plt.hist(images[i*3].ravel(),256)

    plt.title(titles[i*3+1])
    plt.subplot(3,3,i*3+3),plt.imshow(images[i*3+2],'gray')
    plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])
plt.show()
import math
import cmath

dirPath=dir(math)
print(dirPath)

str1= "nimagebi"
tou=tuple(str1)
print(tou)


def printInfo(name,age=25):
    print("name:"+name+"age:"+str(age))

printInfo(name= "jaba")

def numInfo(name,*var):
    for va in var:
        print(name+":"+str(va))

numInfo("javb",1,5,65,4,2,4)

sum = lambda arg1,arg2:arg1+arg2

print(sum(10,20))

def reSomthing(arg1,arg2):
    return arg1,arg1+arg2

print(reSomthing(10,20))   
jb,total=reSomthing(45,56)

print(jb)
print(total)
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np


# # First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# # # Create just a figure and only one subplot
# fig, ax = plt.subplots()
# # ax.plot(x, y)
# ax.set_title('Simple plot')


        # # Create two subplots and unpack the output array immediately
# f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
# ax1.plot(x, y)
# ax1.set_title('Sharing Y axis')
# ax2.scatter(x, y)

        # # Create four polar axes and access them through the returned array
# fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
# axs[0, 0].plot(x, y)
# axs[1, 1].scatter(x, y)

        # # Share a X axis with each column of subplots
# f, axs=plt.subplots(2, 2, sharex='col')
# print(axs)
# ax1.plot(x, y)
# ax1.set_title('Sharing Y axis')
# ax2.scatter(x, y)

        # # Share a Y axis with each row of subplots
# plt.subplots(2, 2, sharey='row')

        # # Share both X and Y axes with all subplots
        # plt.subplots(2, 2, sharex='all', sharey='all')

        # # Note that this is the same as
        # plt.subplots(2, 2, sharex=True, sharey=True)

        # # Create figure number 10 with a single subplot
        # # and clears it if it already exists.
fig, ax = plt.subplots(num=10, clear=True)

plt.show()
import numpy as np

b = np.matrix([[1, 2], [3, 4]])
print(b)
b_asarray = np.asarray(b)
print(b_asarray)

import numpy as np 
import matplotlib as mpl
import matplotlib.pyplot as plt

np.random.seed(19680801)  # seed the random number generator.
data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
print(data['b'])
print(data['a'])

data['d'] = np.abs(data['d']) * 100
print(data)

fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set_xlabel('entry a')
ax.set_ylabel('entry b')

plt.show()
import numpy as np 
import matplotlib as mpl
import matplotlib.pyplot as plt

def my_plotter(ax:plt.axes, data1, data2, param_dict):
    """
    A helper function to make a graph.
    """
    out = ax.plot(data1, data2, **param_dict)
    return out

data1, data2, data3, data4 = np.random.randn(4, 100)  # make 4 random data sets
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7))
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})
ran=np.random.randn(4, 100)



fig, ax = plt.subplots(figsize=(5, 2.7))
x = np.arange(len(data1))
ax.plot(x, np.cumsum(data1), color='blue', linewidth=3, linestyle='--')
l, = ax.plot(x, np.cumsum(data2), color='orange', linewidth=2)
l.set_linestyle(':')

fig, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter(data1, data2, s=2, facecolor='C0', edgecolor='k')



fig, ax = plt.subplots(figsize=(5, 2.7))
ax.plot(data1, 'd', label='data1')
ax.plot(data2, 'd', label='data2')
ax.plot(data3, 'v', label='data3')
ax.plot(data4, 's', label='data4')
ax.legend()


mu, sigma = 115, 15
x = mu + sigma * np.random.randn(10000)
print(x)
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
# the histogram of the data
n, bins, patches = ax.hist(x, 50, density=1, facecolor='C0', alpha=0.75)

ax.set_xlabel('Length [cm]')
ax.set_ylabel('Probability')
ax.set_title('Aardvark lengths\n (not really)')
ax.text(75, .025, r'$\mu=115,\ \sigma=15$')
ax.axis([55, 175, 0, 0.03])
ax.grid(True)

plt.show()

import numpy as np
import pandas as pd

s=pd.Series([1,3,1,np.nan,6,8])

print(s)
import numpy as np
import pandas as pd

dates=pd.date_range("20130101",periods=6)

print(dates)
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

科学熊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值