异想天开

What's the true meaning of light, Could you tell me why

opencv 笔记

日期:2019-07-20 22:26:15
  
最后更新日期:2019-07-20 22:27:09
经同事推荐,昨晚将anaconda + spyder + opencv + tensorflow在windows电脑装好了。发现对对图像常规处理操作,果然非常方便。
[code lang="cpp"]
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import cv2
import numpy as np
import os
import matplotlib.pyplot as plt

#压缩模糊
def compress_distort(inputfile, outfile, quality):
if os.path.exists(outfile):
os.remove(outfile)
if not os.path.exists(inputfile):
return "input file not exists"

img = cv2.imread(inputfile)
quality_type = -1
pic_format = outfile.split(".")[-1].lower()
if (pic_format == "jpg") or (pic_format == "jpeg"):
quality_type = int(cv2.IMWRITE_JPEG_QUALITY)
elif pic_format == "png":
#return "not support"
quality_type = int(cv2.IMWRITE_PNG_COMPRESSION)
elif pic_format == "webp":
quality_type == int(cv2.IMWRITE_WEBP_QUALITY)
if quality_type == -1:
return "not support"

cv2.imwrite(outfile, img, [quality_type, quality])
cv2.imshow("display", cv2.imread(outfile))
cv2.waitKey(0)
cv2.destroyAllWindows()

#高斯模糊
def blur_distort(inputfile, outfile, blurtype):
if os.path.exists(outfile):
os.remove(outfile)
if not os.path.exists(inputfile):
return "input file not exists"

img = cv2.imread(inputfile)
blur = cv2.GaussianBlur(img , (5,5),0)
cv2.imwrite(outfile, img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
cv2.imshow("display", cv2.imread(outfile))
cv2.waitKey(0)
cv2.destroyAllWindows()

#高斯噪声, 给一个高斯分布的噪声,卷积操作
def gauss_noise_distort(inputfile, outfile, noisetype, mean, var):
if os.path.exists(outfile):
os.remove(outfile)
if not os.path.exists(inputfile):
return "input file not exists"

img = cv2.imread(inputfile)
if noisetype == "gauss":
row, col, ch = img.shape
#mean = 0
#var = 0.1
sigma = var**0.5
gauss = np.random.normal(mean, sigma, (row, col, ch))

gauss.reshape((row, col, ch))
noisy = gauss + img
cv2.imwrite(outfile, noisy, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
cv2.imshow("display", cv2.imread(outfile))
cv2.waitKey(0)
cv2.destroyAllWindows()

#灰度图
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
#return np.dot(rgb[...,:3], [0, 1, 0])
#return np.dot(rgb[...,:3], [0.3333, 0.3334, 0.3333])

#sobel算子提取边缘
def test_sobel():
in_file = "D:\\Projects\\anacoda\\11.jpg"
save_file = "D:\\Projects\\anacoda\\2.jpg"
img = cv2.imread(in_file)
x = cv2.Sobel(img, cv2.CV_16S, 1,0)
y = cv2.Sobel(img, cv2.CV_16S, 0,1)
absX=cv2.convertScaleAbs(x)#转回uint8
absY=cv2.convertScaleAbs(y)
dst=cv2.addWeighted(absX,0.5,absY,0.5,0)
a = np.zeros(dst.shape)

dst = rgb2gray(dst)
row, col = dst.shape
for r in range(row):
for c in range(col):
#for ch in range(chanel):
if dst[r]
 > 100:
a[r]
 = dst[r]


#
cv2.imshow("absX",absX)
cv2.imshow("absY",absY)
#cv2.imshow("Result",dst)
cv2.imshow("Result",a)
cv2.waitKey(0)
cv2.destroyAllWindows()

#快速傅里叶变换, 80000个点,频率为4w时出现重复
def test_fft():
x = np.linspace(0, 4*np.pi, 80000)
y = np.cos(x)
tr = np.fft.fft(y)
plt.plot(tr)

#离散余弦变换。 8x8离散余弦矩阵,对一个8x8的矩阵块? 会把能量集中于左上角。原因离散余弦矩阵每一行加起来为0,同时频率上,越到下面的行频率越高。则低频的差值波动更大一些,能量会集中
def test_dct():
img = cv2.imread("D:\\Projects\\anacoda\\1.jpg", 0)
y1 = cv2.medianBlur(img, 3)

#y = rgb2gray(img)
gy = img.astype(np.uint8)
y1 = np.float32(y1)/255.0
#y1 = y1.astype(np.float32)

#y1 = cv2.medianBlur(y1, 3)
#shape = y.shape
#y1 = np.float( y.reshape(1, shape[0]*shape[1]) )/255
#y1.reshape(shape)
y2 = cv2.dct(y1)
y3 = y2.astype(np.uint8)

y4 = cv2.idct(y2)
y4 = np.float32(y4) * 255.0

cv2.imshow("img", gy)
cv2.imshow("dct", y3)
cv2.imshow("idct", y4.astype(np.uint8))
cv2.waitKey(0)
cv2.destroyAllWindows()

#直方图计算,统计为前边界与后边界的个数,描点为1/2
def cal_hisogram(inputfile):
img = cv2.imread(inputfile)
fig,ax=plt.subplots(1,2,figsize=(12,5))
colors=['blue','green','red']

for i in range(3):
hist,x=np.histogram(img[:,:,i].ravel(),bins=256,range=(0,256))
ax[0].plot(0.5*(x[:-1]+x[1:]),hist,label=colors[i],color=colors[i])


ax[0].legend(loc='upper left')
ax[0].set_xlim(0,256)
hist2,x2,y2=np.histogram2d(
img[:,:,0].ravel(),img[:,:,2].ravel(),
bins=(100,100),range=[(0,256),(0,256)])
ax[1].imshow(hist2,extent=(0,256,0,256),origin='lower',cmap='gray')
ax[1].set_ylabel('blue')
ax[1].set_xlabel('red')
plt.show()

def show_img(in_file):
img = cv2.imread(in_file)
newimg = rgb2gray(img)
row, cols = newimg.shape
print(newimg.shape)
img1 = np.zeros((row, cols), np.uint8)
for i in range(row):
for j in range(cols):
img1[i][j] = np.uint8(newimg[i][j])
img2 = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)


cv2.imshow("gray", img1)
cv2.waitKey(0)
cv2.destroyAllWindows()
return img1
[/code]