一、通道的分離與合并
- split(mat)分割圖像的通道
- merge((ch1,ch2, ch3)) 融合多個(gè)通道
import cv2
import numpy as np
img = np.zeros((480, 640, 3), np.uint8)
b,g,r = cv2.split(img)
b[10:100, 10:100] = 255
g[10:100, 10:100] = 255
img2 = cv2.merge((b, g, r))
cv2.imshow('img', img)
cv2.imshow('b', b)
cv2.imshow('g', g)
cv2.imshow('img2', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
二、繪制圖形
利用OpenCV提供的繪制圖形API可以輕松在圖像上繪制各種圖形, 比如直線, 矩形, 圓, 橢圓等圖形.
- line(img, pt1, pt2, color, thickness, lineType, shift) 畫直線
? - img: 在哪個(gè)圖像上畫線
? - pt1, pt2: 開始點(diǎn), 結(jié)束點(diǎn). 指定線的開始與結(jié)束位置
? - color: 顏色
? - thickness: 線寬
? - lineType: 線型.線型為-1, 4, 8, 16, 默認(rèn)為8
? - shift: 坐標(biāo)縮放比例.
- rectangle() 參數(shù)同上 ?畫矩形
- circle(img, center, radius, color, thickness, lineType, shift) 中括號(hào)內(nèi)參數(shù)表示可選參數(shù). 畫圓
- ellipse(img, 中心點(diǎn), 長寬的一半, 角度, 從哪個(gè)角度開始, 從哪個(gè)角度結(jié)束,...)
- polylines(img, pts, isClosed, color, thickness, lineType, shift) 畫多邊形
- fillPoly 填充多邊形
- putText(img, text, org, fontFace, fontScale, color, thickness, lineType, shift) 繪制文本
? - text 要繪制的文本
? - org 文本在圖片中的左下角坐標(biāo)
? - fontFace ?字體類型即字體
? - fontScale 字體大小文章來源:http://www.zghlxwxcb.cn/news/detail-704563.html
import cv2
import numpy as np
img = np.zeros((480, 640, 3), np.uint8)
# cv2.line(img, (10, 20), (300, 400), (0, 0, 255), 5, 4)
# cv2.line(img, (80, 100), (380, 480), (0, 0, 255), 5, 16)
# 畫矩形
# cv2.rectangle(img, (10,10), (100, 100), (0, 0, 255), -1)
# 畫圓
# cv2.circle(img, (320, 240), 100, (0, 0, 255))
# cv2.circle(img, (320, 240), 5, (0, 0, 255), -1)
# 畫橢圓
# cv2.ellipse(img, (320, 240), (100, 50), 15, 0, 360, (0, 0, 255), -1)
#畫多邊形
# pts = np.array([(300, 10), (150, 100), (450, 100)], np.int32)
# cv2.polylines(img, [pts], True, (0, 0, 255))
#填充多邊形
# cv2.fillPoly(img, [pts], (255, 255, 0))
cv2.putText(img, "Hello OpenCV!", (10, 400), cv2.FONT_HERSHEY_TRIPLEX, 3, (255,0,0))
cv2.imshow('draw', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 繪制中文 opencv本身不支持, 因?yàn)闆]有中文字體.我們可以借助pillow來實(shí)現(xiàn)繪制中文文章來源地址http://www.zghlxwxcb.cn/news/detail-704563.html
# 安裝pillow
import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
img = np.full((200, 200, 3), fill_value=255, dtype=np.uint8)
# 導(dǎo)入字體文件.
font_path = 'msyhbd.ttc'
font = ImageFont.truetype(font_path, 15)
img_pil = Image.fromarray(img)
draw = ImageDraw.Draw(img_pil)
draw.text((10, 150), '繪制中文', font=font, fill=(0, 255, 0, 0))
img = np.array(img_pil)
# 中文會(huì)顯示問號(hào)
cv2.putText(img, '中文', (10, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 1)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
到了這里,關(guān)于OpenCV 04(通道分離與合并 | 繪制圖形)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!