绘制几何图形
‘’’ 1’绘制直线
2‘绘制圆形
3’绘制矩形
4‘向图像中添加文字
5’效果展示
import cv2
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
img=np.zeros((512,512,3),np.uint8)
cv.line(img,(0,0),(511,511),(255,0,0),5)
cv.circle(img,(256,256),60,(0,0,255),-1)
cv.putText(img,"hello",(100,150),cv.FONT_HERSHEY_COMPLEX,5,(255,255,255),3)
plt.imshow(img[:,:,::-1])
plt.show()
‘’’
获取并修改图像中的像素点
像素点的改变在图片上比较难以观察,则输出了改变点的像素点
img[100,100]=(0,0,255)
plt.imshow(img[:,:,::-1])
print(img[100,100])
print(img.shape)
print(img.dtype)
print(img.size)
test=cv.imread("opencv_1.png")
print(plt.imshow(test))
print(plt.imshow(test[:,:,::-1]))
b,g,r=cv.split(test)
plt.imshow(b,cmap=plt.cm.gray)
img2=cv.merge((b,g,r))
plt.imshow(img[:,:,::-1])
cv.imshow('opencv_1.png',test)
算术操作
‘’’ 可以将两幅图相加,或者通过numpy操作添加两幅图像, 两幅图像应该具有相同的大小和类型,或者第二个图像可以是标量值 opencv加法是饱和操作,numpy中是模运算
import cv2
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
img1=cv.imread('opencv_1.png');
img2=cv.imread("opencv_2.png");
plt.imshow(img1[:,:,::-1])
img3=cv.add(img2,img1)
img4=img1+img2
print(img3.shape)
img_200x200=cv.resize(img1,(200,200))
img_half=cv.resize(img1,(0,0),fx=0.5,fy=0.5,interpolation=cv.INTER_NEAREST)
cv.imshow("img_half",img_half)
cv.imshow("image",img_200x200)
cv.imshow('img3',img3)
cv.imshow('img4',img4)
图像的混合
img5=cv2.addWeighted(img1,0.7,img2,0.3,0)
cv.imshow('img5',img5)
photo1=cv.imread('opencv_2.png')
cv.imshow("123",photo1)
res=cv.resize(photo1,(0,0),fx=0.5,fy=0.5)
cv.imshow("qw",res)
import numpy as np
import cv2
img = cv2.imread('test.png')
M_crop_dog = np.array([
[1.6, 0, -150],
[0, 1.6, -240]
], dtype=np.float32)
img_dog = cv2.warpAffine(img, M_crop_dog,(400, 400))
cv2.imshow("img_dog", img_dog)
theta=15*np.pi/180
M_shear=np.array([
[1,np.tan(theta),0],
[0,1,0]
],dtype=np.float32)
img_sheared=cv2.warpAffine(img,M_shear,(400,600))
cv2.imshow("img_sheared",img_sheared)
M_rotate=np.array([
[np.cos(theta),-np.sin(theta),0],
[np.sin(theta),np.cos(theta),0]
],dtype=np.float32)
im_rotate=cv2.warpAffine(img,M_rotate,(400,600))
cv2.imshow("im_rotate",im_rotate)
M=np.array([
[1,1.5,-400],
[0.5,2,-100]
],dtype=np.float32)
img_transformed=cv2.warpAffine(img,M,(400,600))
cv2.imshow("img_transformed",img_transformed)
cv2.waitKey(0)
|