Python 結(jié)合opencv實現(xiàn)圖片截取和拼接代碼實踐
實踐環(huán)境
python 3.6.2
scikit-build-0.16.7
win10
opencv_python-4.5.4.60-cp36-cp36m-win_amd64.whl
下載地址:
https://pypi.org/project/opencv-python/4.5.4.60/#files
注意:下載時不用下abi版的,比如 opencv_python-4.6.0.66-cp36-abi3-win_amd64.whl 不能用,
因為數(shù)據(jù)類型為 np.uint8,也就是0~255,
依賴包安裝
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple scikit-build # 解決 ModuleNotFoundError: No module named 'skbuild'問題 pip install opencv_python-4.5.4.60-cp36-cp36m-win_amd64.whl
代碼實踐
示例圖片

代碼
import os
import numpy as np
import cv2
from datetime import datetime
from PIL import Image
def capture_image(image_file_path, left, upper, width, height, target_file_name=None):
'''截取圖片'''
right = left + width
lower = upper + height
if os.path.exists(image_file_path):
image = Image.open(image_file_path)
# width, height = image.size
# print('圖片寬度', width, '圖片高度', height)
head, ext = os.path.splitext(image_file_path)
if not target_file_name:
target_file_name = 'pic_captured%s%s' % (datetime.now().strftime('%Y%m%d%H%M%S%f'), ext)
target_file_path = '%s%s' % (head, target_file_name)
image.crop((left, upper, right, lower)).save(target_file_path)
return target_file_path
else:
error_msg = '圖片文件路徑不存在:%s' % image_file_path
print(error_msg)
raise Exception(error_msg)
def append_picture(image1_path, image2_path):
'''拼接圖片'''
image1 = cv2.imread(image1_path, -1)
shape = image1.shape
height1, width1, channel1 = shape
# print(shape) # 輸出:(315, 510, 4)
# print(image1) # 輸出一3維數(shù)組
# print(len(image1), len(image1[0])) # 輸出:315 510
image2 = cv2.imread(image2_path, -1)
height2, width2, channel2 = image2.shape
total_height = max(height1, height2)
total_width = width1 + width2
dst = np.zeros((total_height, total_width, channel1), np.uint8)
dst[0:height1, 0:width1] = image1
dst[0:height2, width1:total_width] = image2
cv2.imwrite("merge.png", dst)
if __name__ == '__main__':
# 截取圖片
image_path1 = capture_image('example.png', 10, 30, 510, 315)
image_path2 = capture_image('example.png', 520, 30, 518, 315)
append_picture(image_path1, image_path2)運行結(jié)果
截取的圖片


合并的圖片

代碼補(bǔ)充說明
1.imread(filename, flags=None)
filename圖片路徑
函數(shù)返回一個3三元組: (height, width, channel) ,元素中元素從左到右分別表示圖片的高度,寬度,通道數(shù)(彩色圖片是三通道的,每個通道表示圖片的一種顏色( RGB ),對于OpenCV讀取到的圖片的通道順序是 BGR ) ,假設(shè)圖片3元組為 (315, 510, 4) ,表示有315行,即315個二維數(shù)組,510列,即每個二維數(shù)組有510個一維數(shù)組。
flags標(biāo)志位cv2.IMREAD_COLOR:默認(rèn)參數(shù),表示讀入一副彩色圖片,忽略alpha通道,可用1作為實參替代cv2.IMREAD_GRAYSCALE:讀入灰度圖片,可用0作為實參替代cv2.IMREAD_UNCHANGED:讀入完整圖片,包括alpha通道,可用-1作為實參替代
PS: alpha 通道,又稱A通道,是一個8位的灰度通道,該通道用256級灰度來記錄圖像中的透明度復(fù)信息,定義透明、不透明和半透明區(qū)域,其中黑表示全透明,白表示不透明,灰表示半透明
2.imwrite(filename, img, params=None)
將圖片矩陣以文件的形式儲存起來
filename待保存的圖片路徑imgMat或Mat的矢量)要保存的一個或多個圖像。params特定格式的參數(shù)對(paramId_1、paramValue_1、paramId_2、paramValue_2……),參閱cv::ImwriteFlags
3.zeros(shape, dtype=None, order='C')
返回一個用零填充的給定形狀和類型的新數(shù)組( ndarray )
shape整數(shù)或者整數(shù)元組。新數(shù)組的形狀,例如(2, 3)or2。dtype數(shù)據(jù)類型,可選。數(shù)組所需的數(shù)據(jù)類型,比如,numpy.int8。 默認(rèn)numpy.float64。order{'C', 'F'},可選,默認(rèn):'C'。是否在內(nèi)存中按行優(yōu)先(row-major)順序(C語言風(fēng)格)或者列優(yōu)先(column-major)(Fortran風(fēng)格)順序存儲多維數(shù)據(jù)。
示例
>>> import numpy as np # 創(chuàng)建2維數(shù)組 >>> array = np.zeros([2, 3]) >>> print(array) # 輸出一個二維數(shù)組 一個包含2個一維數(shù)組,每個一維數(shù)組包含3個元素 [[0. 0. 0.] [0. 0. 0.]] >>> array = np.zeros([2, 3], np.int64) # 指定數(shù)組元素數(shù)據(jù)類型為int64 >>> print(array) [[0 0 0] [0 0 0]] >>> array = np.zeros([2, 3], np.float64) # 指定數(shù)組元素數(shù)據(jù)類型為float64 >>> print(array) [[0. 0. 0.] [0. 0. 0.]] >>> array = np.zeros([3, 2]) # 輸出一個二維數(shù)組 一個包含3個一維數(shù)組,每個一維數(shù)組包含2個元素 >>> print(array) [[0. 0.] [0. 0.] [0. 0.]] # 創(chuàng)建3維數(shù)組 >>> array = np.zeros((2, 3, 4), np.int8) >>> print(array) # 輸出一個3維數(shù)組 一個包含2個二維數(shù)組,每個二維數(shù)組包含3個一維數(shù)組,每個一維數(shù)組包含4個元素 [[[0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0]]]
4.冒號在Numpy數(shù)組索引中的作用說明
3維數(shù)組為例
ndarray[index1:index2, index3:index4, index5:index6]
indexN:indexM 表示獲取索引在范圍 [indexN, indexM) 內(nèi)的數(shù)組元素(注意,不包含索引為 indexM 的元素),這里的 indexN 代表起始元素索引,可選,默認(rèn)為0, indexM 代表結(jié)束元素索引,可選,默認(rèn)為所在層級數(shù)組元素個數(shù)+1
index1:index2 表示獲取三維數(shù)組中,索引在范圍 [index1, index2) 內(nèi)的數(shù)組元素,即二維數(shù)組
index3:index4 表示獲取上述二維數(shù)組中,索引在范圍 [index3, index4) 內(nèi)的數(shù)組元素,即一維數(shù)組
index5:index6 表示獲取上述一維數(shù)組中,索引在范圍 [index5, index6) 內(nèi)的數(shù)組元素
示例
>>> array = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[11, 12, 13], [14, 15, 16], [17, 18, 19]], [[20, 21, 22], [23, 24, 25], [26, 27, 28]]]) # 創(chuàng)建一個3維 ndarray
>>> array
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[11, 12, 13],
[14, 15, 16],
[17, 18, 19]],
[[20, 21, 22],
[23, 24, 25],
[26, 27, 28]]])
>>> array[:] # 獲取全部元素,等價于array[:, :, :]
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[11, 12, 13],
[14, 15, 16],
[17, 18, 19]],
[[20, 21, 22],
[23, 24, 25],
[26, 27, 28]]])
>>> array[:, :, :]
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[11, 12, 13],
[14, 15, 16],
[17, 18, 19]],
[[20, 21, 22],
[23, 24, 25],
[26, 27, 28]]])
>>> array[1:2] # 獲取索引在[1,2)范圍內(nèi)的二維數(shù)組
array([[[11, 12, 13],
[14, 15, 16],
[17, 18, 19]]])
>>> array[1:] # 獲取索引在[1,3)范圍內(nèi)的二維數(shù)組
array([[[11, 12, 13],
[14, 15, 16],
[17, 18, 19]],
[[20, 21, 22],
[23, 24, 25],
[26, 27, 28]]])
>>> array[:2] # 獲取索引在[0,2)范圍內(nèi)的二維數(shù)組
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[11, 12, 13],
[14, 15, 16],
[17, 18, 19]]])
>>> array[1:2, 1:2] # 獲取索引在[1,2)范圍內(nèi)的二維數(shù)組,二維數(shù)組中只獲取索引在[1,2)范圍內(nèi)的一維數(shù)組
array([[[14, 15, 16]]])
>>> array[1:2, :2] # 獲取索引在[1,2)范圍內(nèi)的二維數(shù)組,二維數(shù)組中只獲取索引在[0,2)范圍內(nèi)的一維數(shù)組
array([[[11, 12, 13],
[14, 15, 16]]])
>>> array[1:2, 1:] # 獲取索引在[1,2)范圍內(nèi)的二維數(shù)組,二維數(shù)組中只獲取索引在[1,3)范圍內(nèi)的一維數(shù)組
array([[[14, 15, 16],
[17, 18, 19]]])
>>> array[1:2, :] # 獲取索引在[1,2)范圍內(nèi)的二維數(shù)組的全部元素
array([[[11, 12, 13],
[14, 15, 16],
[17, 18, 19]]])
>>> array[1:2, 1:2, 1:2] # 獲取索引在[1,2)范圍內(nèi)的二維數(shù)組,二維數(shù)組中只獲取索引在[1,2)范圍內(nèi)的一維數(shù)組,一維數(shù)組中只獲取索引在[1,2)范圍內(nèi)的元素
array([[[15]]])
>>> array[1:2, 1:2, 1:] # 獲取索引在[1,2)范圍內(nèi)的二維數(shù)組,二維數(shù)組中只獲取索引在[1,2)范圍內(nèi)的一維數(shù)組,一維數(shù)組中只獲取索引在[1,3)范圍內(nèi)的元素
array([[[15, 16]]])
>>> array[1:2, 1:2, :2] # 獲取索引在[1,2)范圍內(nèi)的二維數(shù)組,二維數(shù)組中只獲取索引在[1,2)范圍內(nèi)的一維數(shù)組,一維數(shù)組中只獲取索引在[0,2)范圍內(nèi)的元素
array([[[14, 15]]])
>>> array[1:2, 1:2, :] # 獲取索引在[1,2)范圍內(nèi)的二維數(shù)組,二維數(shù)組中只獲取索引在[1,2)范圍內(nèi)的一維數(shù)組,獲取一維數(shù)組的所有元素
array([[[14, 15, 16]]])到此這篇關(guān)于Python 結(jié)合opencv實現(xiàn)圖片截取和拼接的文章就介紹到這了,更多相關(guān)Python opencv圖片截取內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python CategoricalDtype自定義排序?qū)崿F(xiàn)原理解析
這篇文章主要介紹了Python CategoricalDtype自定義排序?qū)崿F(xiàn)原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
pytorch 使用單個GPU與多個GPU進(jìn)行訓(xùn)練與測試的方法
今天小編就為大家分享一篇pytorch 使用單個GPU與多個GPU進(jìn)行訓(xùn)練與測試的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
python 中不同包 類 方法 之間的調(diào)用詳解
這篇文章主要介紹了python 中不同包 類 方法 之間的調(diào)用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
pipreqs?./?--encoding=utf-8?--force?報錯問題解決
本文主要介紹了pipreqs?./?--encoding=utf-8?--force?報錯問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-04-04
Ubuntu18.04中Python2.7與Python3.6環(huán)境切換
這篇文章主要為大家詳細(xì)介紹了Ubuntu18.04中Python2.7與Python3.6環(huán)境切換,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-06-06
Python調(diào)用AnythingLLM API使用流輸出的實現(xiàn)
本文主要介紹了Python調(diào)用AnythingLLM API使用流輸出的實現(xiàn),用于處理長文本或?qū)崟r交互場景,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-03-03

