2.1调用API实现图像缩放(cv2.resize)
图像缩放详解
import cv2
img = cv2.imread('lenacolor.png',1)
imgInfo = img.shape
print(imgInfo)
height = imgInfo[0]
width = imgInfo[1]
mode = imgInfo[2]
dstHeight = int(height*0.5)
dstWidth = int(width*0.5)
dst = cv2.resize(img,(dstWidth,dstHeight))
cv2.imshow('image',dst)
dstInfo = dst.shape
print(dstInfo)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出结果为:
(512, 512, 3)
(256, 256, 3)
2.2源码实现图像缩放
import cv2
import numpy as np
img = cv2.imread('lenacolor.png',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
dstHeight = int(height/2)
dstWidth = int(width/2)
dstImage = np.zeros((dstHeight,dstWidth,3),np.uint8)
for i in range(dstHeight):
for j in range(dstWidth):
iNew = int(i*(height/dstHeight))
jNew = int(j*(width/dstWidth))
dstImage[i,j] = img[iNew,jNew]
cv2.imshow('dst',dstImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
2.3图像剪切
import cv2
img = cv2.imread('lenacolor.png',1)
imgInfo = img.shape
dst = img[100:500,100:300]
cv2.imshow('image',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
2.4调用API实现图像移位(cv2.warpAffine)
import cv2
import numpy as np
img = cv2.imread('lenacolor.png',1)
cv2.imshow('src',img)
height, width = img.shape[:2]
matShift = np.float32([[1,0,100],[0,1,200]])
dst = cv2.warpAffine(img,matShift,(height,width))
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
2.5源码实现图像移位
import cv2
import numpy as np
img = cv2.imread('lenacolor.png',1)
cv2.imshow('src',img)
imgInfo = img.shape
dst1 = np.zeros(img.shape,np.uint8)
dst2 = np.zeros(img.shape,np.uint8)
height = imgInfo[0]
width = imgInfo[1]
for i in range(height-200):
for j in range(width):
dst1[i+200, j] = img[i, j]
for i in range(height):
for j in range(width-100):
dst2[i,j+100]=dst1[i,j]
cv2.imshow('image',dst2)
cv2.waitKey(0)
cv2.destroyAllWindows()