OpenCV 04 (チャネルの分離と結合 | グラフィックスの描画)

1. チャネルの分離と統合

- Split(mat) は画像のチャンネルを分割します
- merge((ch1,ch2, ch3)) は複数のチャンネルをマージします

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()

2.グラフィックを描く


OpenCVが提供する描画APIを使用すると、画像上に直線、長方形、円、楕円などのさまざまな図形を簡単に描画できます。

・line(img、pt1、pt2、color、太さ、lineType、shift)は直線を描きます ・
  img:どの画像に線を引くか
  ・pt1、pt2:始点、終点 直線の開始位置と終了位置を指定しますline
  - color: カラー
  - height: 線の幅
  - lineType: 線の種類 線の種類は -1、4、8、16、デフォルトは 8
  - シフト: 座標の拡大縮小率。

・rectangle()のパラメータは上記と同様 長方形の描画
・circle(img、center、radius、color、thickness、lineType、shift) 角括弧内のパラメータはオプションのパラメータを示します。

- 楕円(画像、中心点、長さと幅の半分、角度、開始角度、終了角度、...)

- ポリライン(img、pts、isClosed、色、太さ、lineType、shift) 多角形を描画します


- fillPoly 塗りつぶしポリゴン


- putText(img, text, org, fontFace, fontScale, color, height, lineType, shift) 描画テキスト
  - text 描画するテキスト
  - org 画像内のテキストの左下隅の座標
  - fontFace フォントの種類フォントです
  - fontScale フォント サイズです

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 自体では中国語の描画はサポートされていません。枕を使用して中国語を描画できます

 # 安装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)
  # 导入字体文件. 
  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)
  
  # 中文会显示问号
  cv2.putText(img, '中文', (10, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 1)
  
  cv2.imshow('img', img)
  cv2.waitKey(0)
  cv2.destroyAllWindows()

おすすめ

転載: blog.csdn.net/peng_258/article/details/132766928
おすすめ