본문 바로가기
파이썬

파이썬 NumPy / OpenCV 2 : 직사각형이 아닌 영역을 자르려면 어떻게합니까?

by º기록 2021. 1. 24.
반응형

모양 (닫힌 폴리 라인)을 만드는 점 집합이 있습니다. 이제 이 모양 내부 의 일부 이미지에서 모든 픽셀을 복사 / 자르고 나머지는 검은 색 / 투명하게 둡니다. 어떻게해야합니까?

예를 들어 다음과 같습니다.

여기에 이미지 설명 입력

그리고 나는 이것을 얻고 싶다.

여기에 이미지 설명 입력

 

해결 방법

 

* edit-알파 채널이있는 이미지와 함께 작동하도록 업데이트되었습니다.

이것은 나를 위해 일했습니다.

마스크를받는 함수에 대해 이미지와 마스크를 별도로 유지하고 싶을 것입니다. 그러나 나는 이것이 당신이 특별히 요구 한 것을 믿는다.

import cv2
import numpy as np

# original image
# -1 loads as-is so if it will be 3 or 4 channel as the original
image = cv2.imread('image.png', -1)
# mask defaulting to black for 3-channel and transparent for 4-channel
# (of course replace corners with yours)
mask = np.zeros(image.shape, dtype=np.uint8)
roi_corners = np.array([[(10,10), (300,300), (10,300)]], dtype=np.int32)
# fill the ROI so it doesn't get wiped out when the mask is applied
channel_count = image.shape[2]  # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,)*channel_count
cv2.fillPoly(mask, roi_corners, ignore_mask_color)
# from Masterfool: use cv2.fillConvexPoly if you know it's convex

# apply the mask
masked_image = cv2.bitwise_and(image, mask)

# save the result
cv2.imwrite('image_masked.png', masked_image)

 

참조 페이지 https://stackoverflow.com/questions/15341538

 

 

반응형

댓글