TensorFlow+OpenCV图像处理( 二 图像几何变换-缩放、剪切、移位)

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]
# 1 放大 缩小 2 等比例 非 2:3
dstHeight = int(height*0.5)
dstWidth = int(width*0.5)
#最近临域插值 双线性插值 像素关系重采样 立方插值
dst = cv2.resize(img,(dstWidth,dstHeight))   #调用API
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) #0-255
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]]) # 2*3矩阵
dst = cv2.warpAffine(img,matShift,(height,width)) #1 原图像 2 移位矩阵 3 行列信息
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

# [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]]
#(0,0)->(100,200)
# (X,Y)= (x+100,y+200)

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()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值