0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python+OpenCVで画像を丸く切り抜いた

Posted at

開発環境

  • Visual Studio Code (Version: 1.85.1)
  • Python 3.11.7
  • numpy 1.26.3
  • opencv-python 4.9.0.80

入力画像

src.png

コード

import cv2
import numpy as np

CROP_RADIUS = 256 
COLOR_WHITE = (255, 255, 255, 255)
src_img = cv2.imread("src.png")

if src_img is None:
    print("Error: Image not loaded")
else:
    src_height, src_width = src_img.shape[:2]
    center_point = (src_width // 2, src_height // 2)
    img = np.zeros((src_height, src_width, 4), dtype=np.uint8)
    img = cv2.circle(img, center_point, CROP_RADIUS, COLOR_WHITE, cv2.FILLED)
    img[:,:,:3] = src_img[:,:,:3]

    cv2.imwrite("circle_cropped.png", img)

出力画像

circle_cropped.png

アンチエイリアス

境界のギザギザが気になったのでアンチエイリアスをかけました。

img = cv2.circle(img, center_point, CROP_RADIUS, COLOR_WHITE, cv2.FILLED,lineType=cv2.LINE_AA)

出力画像

cropped.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?