欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

opencv

程序员文章站 2024-03-25 10:14:28
...
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

int main()
{
	Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);
	cout << "行数=" << m.rows << endl;
	cout << "列数=" << m.cols << endl;
	cout << "矩阵尺寸=" << m.size() << endl;
	cout << "通道数=" << m.channels() << endl;
	cout << "面积=" << m.total() << endl;
	cout << "维数=" << m.dims << endl;
	for (int i = 0; i < m.rows; i++)
	{
		for (int j = 0; j < m.cols; j++)
			cout << m.at<int>(i, j) << ",";
		cout << endl;
	}

	for (int r = 0; r < m.rows; r++)
	{
		const int *ptr = m.ptr<int>(r);
		for (int c = 0; c < m.cols; c++)
			cout << ptr[c] << ",";
		cout << endl;

	}

	if (m.isContinuous())
	{
		int *ptr = m.ptr<int>(0);//去矩阵的第一个值的地址
		for (int n = 0; n < m.rows*m.cols; n++)
			cout << ptr[n] << ",";
	}

	return 0;
}
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

int main()
{
	//Mat image = imread("F:\\opencvpy\\opencvcpp\\pic\\0.jpg",CV_LOAD_IMAGE_GRAYSCALE);  //存放自己图像的路径 
	Mat image = imread("F:\\opencvpy\\opencvcpp\\pic\\0.jpg",CV_LOAD_IMAGE_ANYCOLOR);
	imshow("显示图像", image);
	vector<Mat> planes;
	split(image, planes);
	imshow("B", planes[0]);
	imshow("G", planes[1]);
	imshow("R", planes[2]);
	waitKey(0);
	return 0;
}

 

import cv2 as cv
img = cv.imread('0.jpg',1)
cv.imshow("org", img)
b = img[:,:,0]
g = img[:,:,0]
r = img[:,:,0]
cv.imshow("b",b)
cv.imshow("g",g)
cv.imshow("r",r)
cv.imwrite('x1.jpg',img,[cv.IMWRITE_JPEG_QUALITY,50])
cv.waitKey(0)
opencv几何变换
#像素操作
import cv2
img = cv2.imread("org1.jpg", 1)
(b, g ,r) = img[100, 100]#bgr
print(b, g, r)
print(img.shape)
for i in range(1, 200):
    for j in range(1b, 200):
        img[10+i, 200+j] = (255, 0, 0)
cv2.imshow("orgchangepix",img)
cv2.waitKey(0)

import cv2
#img = cv2.imread("0.jpg", 0)#读取
img = cv2.imread("0.jpg", cv2.IMREAD_COLOR)
#img = cv2.imread("0.jpg", cv2.IMREAD_GRAYSCALE)
cv2.imshow("image", img)
print("image read.")
cv2.imwrite("./write0.jpg", img)#写入 
print("image write.")
img2 = cv2.imread("write0.jpg", 1)
cv2.imshow("writeimg", img2)
print("show image write.")
cv2.waitKey(0)

#仿射变换
import cv2
import numpy as np
img = cv2.imread("org.jpg", 1)
imginfo = img.shape
h = imginfo[0]
w = imginfo[1]
deep = imginfo[2]
#三点决定一个平面
matsrc = np.float32([[0,0],[0,h-1],[w-1,0]])
matdst = np.float32([[50,50],[300,h-200],[w-300,100]])
mataffine = cv2.getAffineTransform(matsrc,matdst)
dst = cv2.warpAffine(img,mataffine,(w,h))
cv2.imshow("dst", dst)
cv2.waitKey(0)

#图像旋转
import cv2
import numpy as np
img = cv2.imread("0.jpg", 1)
cv2.imshow("org", img)
print(img.shape)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
#getRotationMatrix2D 获取旋转矩阵
#warpAffine 实现坐标系仿射变换
matRotate = cv2.getRotationMatrix2D((height*0.5, width*0.5), 45, 0.5)
#换成1,不缩放,图片旋转,超出图像的范围
dst = cv2.warpAffine(img, matRotate, (height, width))
cv2.imshow("dst", dst)
cv2.waitKey(0)

#图像缩放
import cv2
img = cv2.imread("org.jpg", 1)
cv2.imshow("org", img)
imginfo = img.shape
print(imginfo)
h = imginfo[0]
w = imginfo[1]
m = imginfo[2]
dsth = int(h*0.5)
dstw = int(w*0.5)
#最近邻域插值 双线性插值 像素关系重采样 立方插值
dst = cv2.resize(img, (dstw, dsth))
cv2.imshow("imgresize", dst)
cv2.waitKey(0)

#图像缩放
#最近邻域算法
import cv2
img = cv2.imread("org.jpg", 1)
cv2.imshow("org", img)
imginfo = img.shape
h = imginfo[0]
w = imginfo[1]
dsth = int(h/2)
dstw = int(w/2)

dstimg = np.zeros((dsth, dstw, 3), np.uint8)
for i in range(0,dsth):
    for j in range(0,dstw):
        inew = int(i*(h*1.0/dsth))
        jnew = int(j*(w*1.0/dstw))
        dstimg[i,j] = img[inew,jnew]
cv2.imgshow("dst", dstimg)
cv2.waitKey(0)


#图像缩放
#[[A1 A2 B1],[A3 A4 B2]]
# [[A1 A2],[A3 A4]]  [[B1],[B2]]
# newX = A1*x + A2*y+B1
# newY = A3*x +A4*y+B2
# x->x*0.5 y->y*0.5
# newX = 0.5*x
import cv2
import numpy as np
img = cv2.imread('org.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
matScale = np.float32([[0.5,0,0],[0,0.5,0]])
dst = cv2.warpAffine(img,matScale,(int(width),int(height)))
cv2.imshow('dst',dst)
cv2.waitKey(0)

#图像缩放
#[[A1 A2 B1],[A3 A4 B2]]
# [[A1 A2],[A3 A4]]  [[B1],[B2]]
# newX = A1*x + A2*y+B1
# newY = A3*x +A4*y+B2
# x->x*0.5 y->y*0.5
# newX = 0.5*x
import cv2
import numpy as np
img = cv2.imread('org.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
matScale = np.float32([[0.5,0,0],[0,0.5,0]])
dst = cv2.warpAffine(img,matScale,(int(width/2),int(height/2)))
cv2.imshow('dst',dst)
cv2.waitKey(0)

#图片质量
import cv2
img = cv2.imread("org.jpg", 1)
cv2.imshow("org", img)
#cv2.imwrite("orgwritechagequality.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 0])#图像质量变差,变小
#0~100 有损压缩
#cv2.imwrite("orgwritechagequality1.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 100])#图像质量看不出,变小
#cv2.imwrite("orgwritechagequality2.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 50])#图像质量变差,变小
#jpg to png 无损压缩 png有透明属性
cv2.imwrite("jpgtopng1.png", img, [cv2.IMWRITE_PNG_COMPRESSION, 50])
#img2 = cv2.imread("orgwritechagequality2.jpg",1)
#cv2.imshow("orgwritechagequality2", img2)
img2 = cv2.imread("jpgtopng1.png",1)
cv2.imshow("jpgtopng1.png", img2)
cv2.waitKey(0)

#图片剪切
import cv2
img = cv2.imread("org.jpg", 1)
imginfo = img.shape
dst = img[100:200,200:300]
cv2.imshow("dst", dst)
cv2.waitKey(0)

#图片移位
import cv2
import numpy as np
img = cv2.imread("org.jpg", 1)
cv2.imshow("src", img)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]

matshift = np.float32([[1,0,100],[0,1,100]])#2*3
dst = cv2.warpAffine(img, matshift, (height,width))#1 data 2 mat 3 info
#移位矩阵
cv2.imshow("dst", dst)
cv2.waitKey(0)

# [1,0,100],[0,1,200] 2*2 2*1 
# [[1,0],[0,1]]  2*2  A
# [[100],[200]] 2*1   B
# xy C
# A*C+B = [[1*x+0*y],[0*x+1*y]]+[[100],[200]]
# = [[x+100],[y+200]]

#(10,20)->(110,120)

 

#opencv图片特效
#图片融合
#dst = src1*a + src2*(1-a)
import cv2 as cv
import numpy as np
img0 = cv.imread("00.jpg", 1)
img1 = cv.imread("1.jpg", 1)
imginfo0 = img0.shape
imginfo1 = img1.shape
print(imginfo0)
print(imginfo1)
height = imginfo0[0]
width = imginfo0[1]
#ROI
roiH = int(height/2)
roiW = int(width/2)
img0ROI = img0[0:roiH,0:roiW]
img1ROI = img1[0:roiH,0:roiW]
#dst
dst = np.zeros((roiH,roiW,3),np.uint8)
dst = cv.addWeighted(img0ROI, 0.7, img1ROI, 0.3, 0)
#add dst = src1*a + src2*(1-a)

cv.imshow("src0", img0)
cv.imshow("src1", img1)
cv.imshow("dst", dst)

cv.waitKey(0)

#文字图片绘制
'''import cv2
import numpy as np
img = cv2.imread('5.jpg',1)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.rectangle(img,(200,100),(500,400),(0,255,0),3)
# 1 dst 2 文字内容 3 坐标 4 5 字体大小 6 color 7 粗细 8 line type
cv2.putText(img,'this is flow',(100,300),font,1,(200,100,255),2,cv2.LINE_AA)
cv2.imshow('src',img)
cv2.waitKey(0)
'''
import cv2
img = cv2.imread('5.jpg',1)
height = int(img.shape[0]*0.2)
width = int(img.shape[1]*0.2)
imgResize = cv2.resize(img,(width,height))
for i in range(0,height):
    for j in range(0,width):
        img[i+200,j+350] = imgResize[i,j]
cv2.imshow('src',img)
cv2.waitKey(0)

#毛玻璃
import cv2
import numpy as np
import random
img = cv2.imread("1.jpg", 1)
cv2.imshow("org", img)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
print(imginfo)
dst = np.zeros((height,width,3),np.uint8)
mm = 8
for i in range(0,height-mm):
    for j in range(0,width-mm):
        index = int(random.random()*8)#0-8
        dst[i,j] = img[i+index,j+index]
#原理:在遍历像素矩阵在某一区域内的随机选择一个像素点代替当前像素点
cv2.imshow("毛玻璃", dst)
cv2.waitKey(0)

#油画特效
#1 gray 2 7*7 10*10 3 0-255 256 4 640-63 64-127
# 3 10 0-63 99
# 4 count 5 dst = result

import cv2
import numpy as np
img = cv2.imread('org.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dst = np.zeros((height,width,3),np.uint8)
for i in range(4,height-4):
    for j in range(4,width-4):
        array1 = np.zeros(8,np.uint8)
        for m in range(-4,4):
            for n in range(-4,4):
                p1 = int(gray[i+m,j+n]/32)
                array1[p1] = array1[p1]+1
        currentMax = array1[0]
        l = 0
        for k in range(0,8):
            if currentMax<array1[k]:
                currentMax = array1[k]
                l = k
        # 简化 均值
        for m in range(-4,4):
            for n in range(-4,4):
                if gray[i+m,j+n]>=(l*32) and gray[i+m,j+n]<=((l+1)*32):
                    (b,g,r) = img[i+m,j+n]
        dst[i,j] = (b,g,r)
cv2.imshow('dst',dst)
cv2.waitKey(0)

#浮雕效果
import cv2 as cv
import numpy as np

img = cv.imread("1.jpg", 1)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
cv.imshow("src", img)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
#newp = gray0-gray1+150
dst = np.zeros((height,width,1), np.uint8)
for i in range(0, height):
    for j in range(0, width-1):
        grayp0 = int(gray[i, j])
        grayp1 = int(gray[i, j+1])
        newp = grayp0 - grayp1 + 150
        if newp > 255:
            newp = 255
        if newp < 0:
            newp = 0
        dst[i, j] = newp
cv.imshow("dst", dst)
cv.waitKey(0)

#灰度处理
# #imread
#法1 imread
import cv2
import numpy as np
img0 = cv2.imread('0.jpg', 0)
img1 = cv2.imread('0.jpg', 1)
print(img0.shape)
print(img1.shape)
#法2 颜色空间转换
dst = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
#法3
#RGB -> gray (R+G+B)/3
imginfo = img1.shape
height = imginfo[0]
width = imginfo[1]
dstalgh = np.zeros((height,width,3),np.uint8)
for i in range(0, height):
    for j in range(0, width):
        (b, g, r) = img1[i,j]
        gray = (int(b)+int(g)+int(r))/3
        #数据转换防溢出
        dstalgh[i,j] = np.uint8(gray)
#法4 gray = r*0.299+g*0.587+b*0.114
dstalgh1 = np.zeros((height,width,3),np.uint8)
for i in range(0, height):
    for j in range(0, width):
        (b, g, r) = img1[i,j]
        b = int(b)
        g = int(g)
        r = int(r)
        gray = r*0.299+g*0.587+b*0.114
        #数据转换防溢出
        dstalgh1[i,j] = np.uint8(gray)

#算法优化定点优于浮点,位移优于乘除
#gray = r*0.299+g*0.587+b*0.114
dstalgh2 = np.zeros((height,width,1),np.uint8)
for i in range(0, height):
    for j in range(0, width):
        (b, g, r) = img1[i,j]
        b = int(b)
        g = int(g)
        r = int(r)
        #gray = r*0.299+g*0.587+b*0.114  *4 ->
        #gray = (r+g*2+b)/4
        gray = (r+(g<<1)+b)>>2
        dstalgh2[i,j] = np.uint8(gray)
cv2.imshow("grep pic", img0)
cv2.imshow("color pic", img1)
cv2.imshow("gray", dst)
cv2.imshow("dstalgh", dstalgh)
cv2.imshow("dstalgh1", dstalgh1)
cv2.imshow("dstalgh2", dstalgh2)
cv2.waitKey(0)
'''
import cv2
img = cv2.imread("0.jpg", 1)
dst = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", dst)
cv2.waitKey(0)
'''

#矩形绘制
import cv2
import numpy as np
newImageInfo = (500,500,3)
dst = np.zeros(newImageInfo,np.uint8)
#  1 2 左上角 3 右下角 4 5 fill -1 >0 line w
cv2.rectangle(dst,(50,100),(200,300),(255,0,0),5)
# 2 center 3 r
cv2.circle(dst,(250,250),(50),(0,255,0),2)
# 2 center 3 轴 4 angle 5 begin 6 end 7
cv2.ellipse(dst,(256,256),(150,100),0,0,180,(255,255,0),-1)

points = np.array([[150,50],[140,140],[200,170],[250,250],[150,50]],np.int32)
print(points.shape)
points = points.reshape((-1,1,2))
print(points.shape)
cv2.polylines(dst,[points],True,(0,255,255))
cv2.imshow('dst',dst)
cv2.waitKey(0)

#线段绘制
import cv2 as cv
import numpy as np
newimginfo = (500,500,3)
dst = np.zeros(newimginfo, np.uint8)

cv.line(dst,(100,100),(400,400),(0,0,255))

cv.line(dst,(100,200),(400,200),(0,255,255),20)

cv.line(dst,(100,300),(400,300),(0,255,0),20,cv.LINE_AA)

cv.line(dst,(200,150),(50,250),(25,100,255))
cv.line(dst,(50,250),(400,380),(25,100,255))
cv.line(dst,(400,380),(200,150),(25,100,255))

cv.imshow('dst',dst)
cv.waitKey(0)

#边缘检测
#基于灰度图像
#高斯滤波 去燥
#canny
import cv2 as cv
import numpy as np
import random
import math
img = cv.imread("5.jpg", 1)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
cv.imshow("src", img)
#法1
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
imgG = cv.GaussianBlur(gray, (3, 3), 0)
dst = cv.Canny(img, 50, 50)#图片卷积
#法2
#sobel算子模板 图片卷积  阈值判决
# [1 2 1          [ 1 0 -1
#  0 0 0            2 0 -2
# -1 -2 -1 ]       1 0 -1 ]
# [1 2 3 4] [a b c d] a*1+b*2+c*3+d*4 = dst
# sqrt(a*a+b*b) = f>th
dst2 = np.zeros((height, width, 1), np.uint8)
for i in range(0, height-2):
    for j in range(0, width-2):
        gy = gray[i, j] * 1 + gray[i, j + 1] * 2 + gray[i, j + 2] * 1 - gray[i + 2, j] * 1 - gray[i + 2, j + 1] * 2 - gray[i + 2, j + 2] * 1
        gx = gray[i, j] + gray[i + 1, j] * 2 + gray[i + 2, j] - gray[i, j + 2] - gray[i + 1, j + 2] * 2 - gray[i + 2, j + 2]
        grad = math.sqrt(gx*gx+gy*gy)
        if grad > 50:
            dst2[i, j] = 255
        else:
            dst2[i, j] = 0
cv.imshow("dst", dst)
cv.imshow("dst2", dst2)
cv.waitKey(0)

#颜色反转
import cv2
import numpy as np

# img = cv2.imread("0.jpg", 1)
img = cv2.imread("org.jpg", 1)
cv2.imshow("org", img)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dst = np.zeros((height, width, 1), np.uint8)
dstcolor = np.zeros((height, width, 3), np.uint8)
# 灰色图像颜色反转
for i in range(0, height):
    for j in range(0, width):
        dst[i, j] = 255 - gray[i, j]

# 彩色图像颜色反转
for i in range(0, height):
    for j in range(0, width):
        (b, g, r) = img[i, j]
        dstcolor[i, j] = (255 - b, 255 - g, 255 - r)

cv2.imshow("gray", dst)
cv2.imshow("colorrever", dstcolor)
cv2.waitKey(0)

#颜色风格
#RGB 分量乘系数增强
import cv2 as cv
import numpy as np
img = cv.imread("org.jpg", 1)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
cv.imshow("src", img)
dst = np.zeros((height,width,3),np.uint8)
for i in range(0,height):
    for j in range(0,width):
        (r,g,b) = img[i,j]
        b = b*1.5
        g = g*1.5
        if b > 255:
            b = 255
        if g > 255:
            g = 255
        dst[i,j] = (r,g,b)
cv.imshow("dst", dst)
cv.waitKey(0)

#马赛克
import cv2
import numpy as np

img = cv2.imread("1.jpg", 1)
cv2.imshow("org", img)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
print(imginfo)
for m in range(100,600):
    for n in range(100,900):
        #10*10
        if m%20 == 0 and n%20 == 0:
            #(b,g,r) = img[m,n]
            for i in range(0,20):
                for j in range(0,20):
                    img[m+i,n+j] = img[m,n]
cv2.imshow("dst", img)
cv2.waitKey(0)
#opencv图片美化
#中值滤波 3*3
import cv2 as cv
import numpy as np
img = cv.imread("org1.jpg",1)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
img = cv.cvtColor(img,cv.COLOR_RGB2GRAY)

dst = np.zeros((height,width,3),np.uint8)
collect = np.zeros(9,np.uint8)
for i in range(-1,height-1):
    for j in range(-1,width-1):
        k=0
        for m in range(-1,2):
            for n in range(-1,2):
                gray = img[i+m,j+n]
                collect[k] = gray
                k=k+1
        for k in range(0,9):
            p1 = collect[k]
            for t in range(k+1,9):
                if p1<collect[t]:
                    mid = collect[t]
                    collect[t] = p1
                    p1 = mid
        dst[i,j] = collect[4]

cv.imshow('orggray',img)
cv.imshow('dst',dst)
cv.waitKey(0)

#亮度增强
import cv2 as cv
import numpy as np
img = cv.imread("org.jpg",1)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
cv.imshow("org", img)

dst = np.zeros((height,width,3),np.uint8)
for i in range(0,height):
    for j in range(0,width):
        (b,g,r) = img[i,j]
        nb = int(b) + 40
        ng = int(g) + 40
        nr = int(r) + 40
        if nb>255:
            nb = 255
        if ng > 255:
            ng = 255
        if nr > 255:
            nr = 255
        dst[i,j] = (nb,ng,nr)
cv.imshow("dst",dst)
cv.waitKey(0)

#图像修补
import cv2 as cv
import numpy as np
img = cv.imread("org.jpg", 1)
cv.imshow("org",img)
#破坏图像
for i in range(300,500):
    img[i,300] = (255,255,255)
    img[i,301] = (255,255,255)
    img[i,299] = (255,255,255)
for i in range(150,500):
    img[350,i] = (255,255,255)
    img[351,i] = (255,255,255)
    img[249,i] = (255,255,255)
cv.imwrite("damage.jpg",img)
#修补图像
img1 = cv.imread("damage.jpg",1)
imginfo = img1.shape
height = imginfo[0]
width = imginfo[1]
paint = np.zeros((height,width,1),np.uint8)

for i in range(300,500):
    paint[i,300] = 255
    paint[i,301] = 255
    paint[i,299] = 255
for i in range(150,500):
    paint[350,i] = 255
    paint[351,i] = 255
    paint[249,i] = 255
imgdst = cv.inpaint(img1,paint,3,cv.INPAINT_TELEA)

cv.imshow("damage",img)
cv.imshow("paint",paint)
cv.imshow("imgdst",imgdst)
cv.waitKey(0)

#图片合成视频
import cv2 as cv
img = cv.imread('y/y0.jpg')
imginfo = img.shape
size = (imginfo[1],imginfo[0])
print(size)
videoWrite = cv.VideoWriter('2.avi',-1,5,size)
#写入对象 编码器 帧率 size
for i in range(1,76):
    filename = 'y/'+'y'+str(i)+'.jpg'
    img = cv.imread(filename)
    videoWrite.write(img)
print("endl.")

#彩色图片直方图
import cv2 as cv
import numpy as np
def imageHist(img, type):
    color = (255,255,255)
    windowname = "Gray"
    if type == 31:
        color = (255,0,0)
        windowname = "B hist"
    elif type == 32:
        color = (0,255,0)
        windowname = "G hist"
    elif type == 33:
        color = (0,0,255)
        windowname = "R hist"
    hist = cv.calcHist([img],[0],None,[256],[0.0,255.0])
    minv,maxv,minl,maxl = cv.minMaxLoc(hist)#最小最大值的坐标
    histImg = np.zeros([256,256,3],np.uint8)
    for h in range(256):
        intenNormal = int(hist[h]*256/maxv)
        cv.line(histImg,(h,256),(h,256-intenNormal),color)
    cv.imshow(windowname,histImg)
    return histImg

img = cv.imread("org.jpg",1)
channels = cv.split(img)#分解成bgr三个通道
for i in range(0,3):
    imageHist(channels[i],31+i)
cv.waitKey(0)

#彩色图片直方图源码
#统计每个像素灰度出现的概率
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread("org.jpg", 1)
cv.imshow("org", img)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
count_b = np.zeros(256,np.float)
count_g = np.zeros(256,np.float)
count_r = np.zeros(256,np.float)
for i in range(0,height):
    for j in range(0,width):
        (b,g,r) = img[i,j]
        index_b = int(b)
        index_g = int(g)
        index_r = int(r)
        count_b[index_b] = count_b[index_b]+1
        count_g[index_g] = count_g[index_g]+1
        count_r[index_r] = count_r[index_r]+1
for i in range(0,256):
    count_b[i] = count_b[i]/(height*width)
    count_g[i] = count_g[i] / (height * width)
    count_r[i] = count_r[i] / (height * width)

x = np.linspace(0,255,256)
yb = count_b
plt.figure()
plt.bar(x,yb,0.9,alpha=1,color='b')
yg = count_g
plt.figure()
plt.bar(x,yg,0.9,alpha=1,color='g')
yr = count_r
plt.figure()
plt.bar(x,yr,0.9,alpha=1,color='r')

plt.show()
cv.waitKey(0)

#灰度直方图源码实现
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread("org.jpg",1)
cv.imshow("org", img)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
count = np.zeros(256,np.float)
#统计每个像素灰度出现的概率
for i in range(0,height):
    for j in range(0,width):
        pixel = gray[i,j]
        index = int(pixel)
        count[index] = count[index]+1
for i in range(0,255):
    count[i] = count[i]/(height*width)
x = np.linspace(0,255,256)
y = count
plt.bar(x,y,0.9,alpha=1,color='b')
plt.show()
cv.waitKey(0)


#直方图均衡化
import cv2 as cv
import numpy as np
img = cv.imread("org.jpg", 1)
cv.imshow("org", img)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow("gray org", gray)
#灰度直方图均衡化
dstgray = cv.equalizeHist(gray)
#彩色直方图均衡化
(b,g,r) = cv.split(img)#通道分解
bh = cv.equalizeHist(b)
gh = cv.equalizeHist(g)
rh = cv.equalizeHist(r)
colorhist = cv.merge((bh,gh,rh)) #通道合成
#yuv 直方图均衡化
imgyuv = cv.cvtColor(img,cv.COLOR_BGR2YCrCb)
channelyuv = cv.split(imgyuv)
channelyuv[0] = cv.equalizeHist(channelyuv[0])
channel = cv.merge(channelyuv)
rst = cv.cvtColor(channel,cv.COLOR_YCrCb2BGR)

cv.imshow("gray hist", dstgray)
cv.imshow("colorhist",colorhist)
cv.imshow("yuvhist", rst)

cv.waitKey(0)


#磨皮美白
import cv2 as cv
import numpy as np
img = cv.imread("org1.jpg",1)
imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
cv.imshow("org", img)

#法1
dst = np.zeros((height,width,3),np.uint8)
for i in range(0,height):
    for j in range(0,width):
        (b,g,r) = img[i,j]
        '''
        nb = int(b) + 40
        ng = int(g) + 40
        nr = int(r) + 40
        '''
        nb = int(b*1.3) + 40
        ng = int(g*1.2) + 40

        if nb>255:
            nb = 255
        if ng > 255:
            ng = 255
        '''if nr > 255:
            nr = 255'''
        '''dst[i,j] = (nb,ng,nr)'''
        dst[i, j] = (nb, ng, r)

#法2 双边滤波
dst1 = cv.bilateralFilter(img,15,35,35)
cv.imshow("dst",dst)
cv.imshow("dst1",dst1)
cv.waitKey(0)

#视频分解图片
#视频分解
import cv2 as cv
cap = cv.VideoCapture("3.avi")
isOpened = cap.isOpened()
print(isOpened)
fps = cap.get(cv.CAP_PROP_FPS)
height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
print(fps,height,width)
i = 0
while(isOpened):
    (flag,frame) = cap.read()
    if flag==True and i%100 == 0:
        filename = 'y4/' + str(int(i / 100)) + '.jpg'
        print(filename)
        cv.imwrite(filename,frame,[cv.IMWRITE_JPEG_QUALITY,100])
    i = i + 1
print('endl!')

#高斯均值滤波
import cv2 as cv
import numpy as np
img = cv.imread("org1.jpg",1)

imginfo = img.shape
height = imginfo[0]
width = imginfo[1]
#高斯滤波
dst = cv.GaussianBlur(img,(5,5),1.5)
print("GaussianBlur")
#均值滤波6*6 1 /36
dst1 = np.zeros((height,width,3),np.uint8)
for i in range(0,height-3):
    for j in range(0,width-3):
        sumb = int(0)
        sumg = int(0)
        sumr = int(0)
        for m in range(-3,3): #-3,-2,-1,0,1,2
            for n in range(-3,3):
                (b,g,r) = img[i+m,j+n]
                sumb = sumb + int(b)
                sumg = sumg + int(g)
                sumr = sumr + int(r)
        b = np.uint8(sumb/36)
        g = np.uint8(sumg / 36)
        r = np.uint8(sumr / 36)
        dst1[i,j] = (b,g,r)
print("qqq")
cv.imshow("org", img)
cv.imshow("dst", dst)
cv.imshow("dst1",dst1)
cv.waitKey(0)

#人脸识别
# load xml load jpg hear gray detect draw
import cv2 as cv
import numpy as np
face_xml = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_xml = cv.CascadeClassifier('haarcascade_eye.xml')
img = cv.imread('x1.jpg')
cv.imshow('src',img)

gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
faces = face_xml.detectMultiScale(gray,1.3,5)
print('face = ',len(faces))

for(x,y,w,h) in faces:
    cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_face = gray[y:y+h,x:x+w]
    roi_color = img[y:y+h,x:x+w]

    eyes = eye_xml.detectMultiScale(roi_face)
    print('eye = ',len(eyes))
    for (ex,ey,ew,eh) in eyes:
        cv.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0))

cv.imshow('dst', img)
cv.waitKey(0)