opencv圖像縮放及編碼模仿實現(python)

用opencv的API實現縮放非常的簡單

#用API實現圖片縮放
import cv2
img = cv2.imread('c.jpg', 1) #後面的1表示彩色,0表示黑白
shape = img.shape #獲取圖像的寬、高、顏色層數
height = shape[0]  #!!!重點,shape[0]表示高,我輸錯調了一個鐘
width = shape[1]
destHeight = int(height * 0.1) #目標大小
destWidth = int(width * 0.1)
img = cv2.resize(img, (destWidth, destHeight)) ##核心API
cv2.imshow('img',img) #顯示圖片
print('end')
cv2.waitKey(0)

最近鄰插值法原理很簡單,就是找在原圖像中找相應的點相素 : 將變換後的圖像中的原像素點最鄰近像素的灰度值賦給原像素點的方法。百度很多,可以查一下,以下是python實現,如不懂numpy,建議好好學一下

# 自己的編碼實現圖片縮放:最近鄰插值法
import numpy as np
import cv2
img = cv2.imread('c.jpg', 1)
shape = img.shape
height = shape[0]
width = shape[1]
imgDeep = shape[2]

destWidth = int(width * 0.2)
destHeight = int(height * 0.2)

destImg = np.zeros((destHeight, destWidth, imgDeep), np.uint8)#目標圖像矩陣,opencv讀入的數據其實也是一個矩陣

for i in range(0, destHeight):
    for j in range(0, destWidth):
        iNew = int(i * (height*1.0 / destHeight))
        jNew = int(j * (width*1.0 / destWidth))
        destImg[i,j] = img[iNew, jNew]
print('end')
cv2.imshow('destImg', destImg)
cv2.waitKey(0)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章