python-opencv及python的常用操作

使一个图像填充黑色或白色:img[…] = 0或255
变灰度: img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
复制:img_copy = img.copy()
取图像的长宽通道数:img.shape 即:彩色:rows, cols, channels = img.shape 灰度:rows, cols = img.shape
用标准正太分布初始化矩阵:mix = np.random.random((3,3))
用一个范围的整数初始化矩阵:mix = np.random.randint(0,100,size = (3,3))
乘以一个正太分布数:x = np.random.random()*y
判断图像是彩色还是灰度:
if img.ndim == 2#灰度
if img.ndim == 3#彩色

对图像单个像素进行操作:
灰度:img[y,x] = 255
彩色:
img[y,x,0] = 255
img[y,x,1] = 255
img[y,x,2] = 255

python主函数:if name == ‘main‘:
对通道进行分离:b, g, r = cv2.split(img)
对其中一个通道进行分离: b = cv2.split(img)[0]
对分离后的通道进行显示: cv2.imshow(‘b’,b)
对分离后的通道进行合并: img_merge = cv2.merge([b,g,r])
创建图像: img_creat = np.zeros((img.shape[0],img.shape[1]),dtype = img.dtype)或img_creat = np.zeros([500,500,3],np.uint8)其中3为通道数
把单通道图像赋给创建好的图像:img_creat[:,:] = img[:,:,0]或img[:,:,1]或img[:,:,2]
把图像赋给创建好的图像:img_creat[:,:,:] = img[:,:,:]
查看numpy的矩阵或向量的数据类型:print arr.dtype
转换numpy的矩阵或向量的数据类型:arr1 = arr.astype(np.float64)或arr2 = arr1.astype(arr0.dtype)
创建字符串向量/数组:string =np.array([“1”,”3”,”2”,”4”],dtype = np.string_)
创建整型向量/数组: arr = np.array([1,3,4,6])
统计一个图像上每个像素值的个数:hist = cv2.calcHist([img], [0]#通道, None, [256], [0.0,255.0])
统计一个矩阵元素的最大值、最小值及他们的位置: minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist)
对矩阵的每个元素四舍五入:

>>> np.around([0.37, 1.64])
array([ 0.,  2.])
>>> np.around([0.37, 1.64], decimals=1)
array([ 0.4,  1.6])
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([ 0.,  2.,  2.,  4.,  4.])
>>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
array([ 1,  2,  3, 11])
>>> np.around([1,2,3,11], decimals=-1)
array([ 0,  0,  0, 10])

创建矩阵:mix = np.arange(4).reshape(2,2)
链接两个向量:

>>> np.hstack([np.array([1, 2, 3]), np.array([4, 5, 6])])
[1, 2, 3, 4, 5, 6]

组合两个向量:

>>> np.column_stack([np.array([1, 2, 3]), np.array([4, 5, 6])])
[[1, 4]
 [2, 5]
 [3, 6]]

把多个向量祝贺组合变成矩阵:

>>>np.vstack([np.array([1, 2, 3]), np.array([4, 5, 6])])或np.row_stack([np.array([1, 2, 3]), np.array([4, 5, 6])])
[[1, 2, 3]
 [4, 5, 6]]

反转矩阵:mix = np.flipud(mix) #行的排列顺序的颠倒
对数组中的元素缩放到一个指定范围:cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX)
画多边形:cv2.polylines(img,[pts],False,color)
把数组或矩阵中的全部元素转换为整数:hist1 = np.int32(hist)
在某个范围内取值:for i in range(200,300)
腐蚀:img_eroded = cv2.erode(img,kernel)
膨胀:img_dilated = cv2.dilate(img,kernel)
对腐蚀或膨胀中kernel的定义:kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
开运算:先腐蚀后膨胀————闭运算相反
开运算:img_opened = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) #其中kernel与腐蚀与膨胀的定义一样
闭运算:img_closed = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
边缘检测的一种方法:膨胀-腐蚀
两图像相减:img_result = cv2.absdiff(img_dilated, img_eroded)
二值化: reVal, img_result = cv2.threshold(img_result, 40, 255, cv2.THRESH_BINARY) #其中result为所求对象
对像素值取反:img_result_over = cv2.bitwise_not(img_result)
在图像上画圆:cv2.circle(img,(j,i),10,(255,0,0))
blur滤波(取每个像素周围像素的均值):dst = cv2.blur(img, (5, 5))等效于dst = cv2.boxFilter(img, -1, (5, 5))
高斯模糊:dst = cv2.GaussianBlur(img, (5,5), 1.5)
中值滤波(可消除椒盐):dst = cv2.medianBlur(img, 5)
Resize图片的大小:
dst = cv2.resize(img, (img1.shape[0], img1.shape[1]))
放大或缩小原图:dst = cv2.resize(img,None,fx=2,fy=2)

两张尺寸一样的图片叠加:img_overlay = cv2.addWeighted(img1, 0.6, img2, 0.4, 0)
把数组或矩阵中的元素转化为8位无符号整型:dst = cv2.convertScaleAbs(src)
读取视频:capture = cv2.VideoCapture(video)
读取视频的每帧:
while 1:
ret, img = capture.read()
cv2.imshow(‘video’, img)
if cv2.waitKey(20) & 0xFF == ord(‘q’):
break
capture.release()
cv2.destroyAllWindows()

输出十六进制:print(‘%x’%key)
把字符转成ascii码:val = ord(‘q’)
把ascii码转成字符:char = chr(65)
sobel算子(一种带有方向的过滤器):x = cv2.Sobel(img,cv2.CV_16S,1,0) 或x = cv2.Sobel(img,cv2.CV_16S,0,1)
在一张图像上选择一片区域贴另一张图:
from PIL import Image
img_base = Image.open(‘/home/jc/桌面/opencv练习/53.jpg’)
img_ps = Image.open(‘/home/jc/桌面/opencv练习/未标题-3.jpg’)
img_base.paste(img_ps, box)其中box = (300, 64, 300+rows, 64+cols)
img_base.show()
base_img.save(‘/home/jc/桌面/opencv练习/h.jpg’)

输出一张图片的大小:print img.size
Laplacian算子:dst = cv2.Laplacian(img, cv2.CV_16S, ksize = 3)
Canny边缘检测算子: canny = cv2.Canny(img1, 50, 150) 先对原图片进行高斯模糊得到img1
把数字转化为字符:x = str(4)
删除数组中指定元素:list.remove(元素)
删除数组中指定下标的元素:del list[i]
删除列表最后一个元素:list.pop()
在数组中追加元素:x.append(元素)
在两个数之间遍历:for i in range(x1, x2):
在图像上画矩形:cv2.rectangle(img, (x0,x1), (x2, x3), (255,0,0), 3)
对小数取整:x1 = int(x0)
对取文件中所有行组成一个列表:
f = open(path,’r’)
lines = f.readlines()

对文件进行写操作并覆盖原文件中的数据:f = open(path, ‘w’)
把列表中的信息写入一个文件中(每个元素一行):
f = open(path, ‘w+’) #若文件不存在,则自动创建
f.writelines(lines)
长宽在函数中的位置:
img = np.zeros([y,x,3], dtype = np.uint8) #其中x为图像横坐标的长度
img1[y, x, 0] = img[y, x, 0] #x为图像横坐标的长度
print img.shape—>(y,x,3) #x为图像横坐标的长度
cv2.line(img, (x0, y0), (x1, y1), (255, 0, 0)) #x0为图像横坐标
处理视频时,opencv只支持avi,生成的视频不能大于2G,且不能添加音频。
把多张图片制作成视频:
savefile = ‘/home/jc/图片/hi.avi’
fourcc = cv2.VideoWriter_fourcc(‘M’, ‘J’, ‘P’, ‘G’)
fps = 5
out = cv2.VideoWriter(savefile, fourcc, fps, (img.clos, img.rows))
for root, dirs, files in os.walk(path)
for file in files:
file_path = os.path.join(path,file)
img = os.imread(file_path)
out.write(img)
cv2.waitKey(1)

读取视频帧,写入视频:
savefile = ‘/home/jc/图片/hi.avi’
fourcc = cv2.VideoWriter_fourcc(‘M’, ‘J’, ‘P’, ‘G’)
fps = 5
out = cv2.VideoWriter(savefile, fourcc, fps, (img.clos, img.rows))
video = (‘/home/jc/视频/Wildlife.avi’)
capture=cv2.VideoCapture(video)
while 1:
ret, img=capture.read()
out.write(img)
cv2.waitKey(1)

腐蚀或膨胀时使用椭圆kernel会使图像平滑:kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
动态创建变量:
createVar = locals()
for c in range(30):
createVar[‘img_ccopy’ + str(c)] = np.zeros([567, 567, 3], np.uint8)

复制文件:shutil.copyfile(‘oldfile’, ‘newfile’) #oldfile和newfile只能是文件
复制一个文件夹中的内容到另一个文件夹: shutil.copy(‘oldfile’, ‘newdir’)
移动文件:shutil.move(‘oldfile_path’, ‘newfile_path’)
删掉文件夹及其中的全部内容:shutil.rmtree(path)
仅能删掉空目录:os.rmdir(path)
判断文件或文件夹是否存在:os.path.exists(path)
判断是否为文件夹:os.path.isdir(path)
判断是否为文件:os.path.isfile(path)
对字符串进行两次分割:
string = “www.gziscas.com.cn”
print(string.split(‘.’,2)) –> [‘www’, ‘gziscas’, ‘com.cn’]

u1, u2, u3 =string.split(‘.’,2)
print(u1) –> www
print(u2) –> gziscas
print(u3) –> com.cn

分离路径与文件名:os.path.split(path)
计时函数(单位:秒):
start = time.time()
函数体
end = time.time()
print end - start

随机在取文件夹中的文件或文件夹:
for root, dirs, files in os.walk(path)
c = len(dirs)
break
path_dir = os.path.join(path, dirs[np.random.randint(0, c)])

按列表中元素的某种元素进行排序:
L = [(‘b’,2),(‘e’,1),(‘c’,3),(‘d’,4)]
L.sort(key=lambda x:x[1]) #若降序排列,则:L.sort(key=lambda x:x[1], reverse=True)
print L –> [(‘e’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4)]

递归创建目录:
os.makedirs(path)
动态变量:
creatVar = lacals()
for i in range(11):
creatVar[‘color’ + str(i8)] = np.zeros([567, 567, 3], np.uint8)

creatSub = lacals()
for i in range(11):
creatSub[‘color1’ + str(i)] = 0
其中creatVar[‘color’ + str(10)]与creatSub[‘color1’ + str(0)]变量名相同,发生冲突

输出某一元素在列表中的位置:
l = [‘d’, ‘a’, 1, 3, 55, 24, 53]
print l.index(‘a’)

format的用法:
print ‘{:,}’.format(1234567893444)–>1,234,567,893,444
print ‘{:x}’.format(123)–>7b
print ‘{0},{1}’.format(‘hello’, 24)–>hello,24
print ‘{},{}’.format(‘hello’, 24)–>hello,24
print ‘{name},{age}’.format(name = ‘jc’, age = 24)–>jc,24
print ‘{:>8}’.format(1234)–> 1234
print ‘{:a>8}’.format(1234)–>aaaa1234
print ‘{:.2f}’.format(1234.435525)–>1234.44

glob.glob()的用法(寻找满足条件的所有文件):
for i in glob.glob(‘/home/jc/图片/test//.jpg’):
img = cv2.imread(i)

写xml文件时,坐标的格式一定是整型而非字符,否则可以训练单不能识别。

猜你喜欢

转载自blog.csdn.net/a_z666666/article/details/80364840