import cv2
import numpy as np
import matplotlib.pyplot as plt
'''获取修改像素值'''
img = cv2.imread('cat1.jpg')
px=img[100,100]
print(px)
blue=img[100,100,0]
print(blue)
img[100,100]=[0,0,0]
print(img[100,100])
'''获取像素值及修改的更好方法'''
print(img.item(10,10,2))
img.itemset((10,10,2),100)
print(img.item(10,10,2))
'''获取图像属性
图像的属性包括:行,列,通道,图像数据类型,像素数目等
img.shape 可以获取图像的形状。他的返回值是一个包含行数,列数, 通道数的元组。
如果图像是灰度图,返回值仅有行数和列数。
img.size 可以返回图像的像素数目
img.dtype 返回的是图像的数据类型.
注意:在debug时 img.dtype 非常重要。因为在 OpenCV-Python代码中经常出现数据类型的不一致。
'''
print(img.shape)
print(img.size)
print(img.dtype)
#复制区域
img = cv2.imread('cat1.jpg')
head=img[40:200,330:500]
img[40:200,40:210]=head
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
b,g,r=cv2.split(img)
img=cv2.merge(b,g,r)
b=img[:,:,0]
'''当像素值高于阈值时,我们给这个像素赋予一个新值(可能是白色),否则我们给它赋予另外一种颜色(也许是黑色)。
这个函数就是 cv2.threshhold()。这个函数的第一个参数就是原图像,原图像应该是灰度图。
第二个参数就是用来对像素值进行分类的阈值。第三个参数 就是当像素值高于(有时是小于)阈值时应该被赋予的
新的像素值。
'''
img=cv2.imread('hui.png',0)
ret,thresh1=cv2.threshold(img,127,255,cv2.THRESH_BINARY)
ret,thresh2=cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3=cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
ret,thresh4=cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
ret,thresh5=cv2.threshold(img,127,255,cv2.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()
img = cv2.imread('chess.jpg',0) # 中值滤波 img = cv2.medianBlur(img,5)
ret,th1 = cv2.threshold(img,70,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,43,60)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,91,50)
titles = ['Original Image', 'Global Thresholding (v = 127)',
'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
cv2.imshow("cir", img)
cv2.imshow("cir1", th1)
cv2.imshow("cir2", th2)
cv2.imshow("cir3", th3)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.adaptiveThreshold用法、参数如下:
img = cv2.imread('cat1.jpg')
#2d卷积
kernel = np.ones((5,5),np.float32)/25
dst = cv2.filter2D(img,-1,kernel)
blur = cv2.blur(img,(5,5))#平均
blur1 = cv2.GaussianBlur(img,(5,5),0)#高斯模糊
median = cv2.medianBlur(img,5)#中值模糊
blur2 = cv2.bilateralFilter(img,9,75,75)#双边滤波
cv2.imshow("img", img)
cv2.imshow("dst", dst)
cv2.imshow('blur',blur)
cv2.imshow('blur1',blur1)
cv2.imshow('median',median)
cv2.imshow('blur2',blur2)
cv2.waitKey(0)
cv2.destroyAllWindows()
img = cv2.imread('chess.jpg',0)
edges = cv2.Canny(img,300,600)
cv2.imshow("cir", img)
cv2.imshow("cir2", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
canny的参数说明和具体步骤如下: