728x90
반응형
https://aihints.com/how-to-draw-bounding-box-in-opencv-python/
이미지 내 특정 그림을 포함하는 bbox만을 남겨두고, 나머지는 crop해버리는 코드
def make_inner_crop():
# target_lst is list of cropped image,
# we're going to remove the padding area, only remain the inner text(figure) area.
# save the result to remove padding area.
target_lst = glob.glob("./crop/*")
result_dir = "./double_crop"
os.makedirs(result_dir, exist_ok=True)
# Crop inner image, remove white padding area
for file in target_lst:
# load image
target = cv2.imread(file)
# convert to gray
target_gray = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(target_gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
for i in contours:
x,y,w,h = cv2.boundingRect(i)
#cv2.rectangle(target, (x, y), (x + w, y + h), (255,0,0), 1)
#cv2.imwrite("./vis/{}_inner.jpg".format(os.path.splitext(os.path.basename(file))[0]), target)
crop = target[y:y+h, x:x+w]
# save
basename = os.path.splitext(os.path.basename(file))[0]
cv2.imwrite(os.path.join(result_dir, "{}_inner.jpg".format(basename)), crop)
728x90
반응형
'사소한 Tip . 오류 해결법 > python' 카테고리의 다른 글
[python] random.sample with ordering(랜덤 추출하면서 순서 유지) (0) | 2023.08.04 |
---|---|
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() (0) | 2023.08.01 |
[Python/Google translator]구글 번역 API 파이썬 (0) | 2023.06.05 |
[python] tuple element sum / 요소 합 (0) | 2023.02.16 |
[python] 파일 리스트 읽고, 특정 파일 외 나머지 삭제하기 (0) | 2023.02.15 |