programing

Python을 사용하여 OpenCV에서 이미지를 자르는 방법

coolbiz 2022. 11. 3. 23:08
반응형

Python을 사용하여 OpenCV에서 이미지를 자르는 방법

OpenCV를 사용하여 이전에 PIL에서 했던 것처럼 이미지를 자르는 방법은 무엇입니까?

PIL에서의 작업 예시

im = Image.open('0.png').convert('L')
im = im.crop((1, 1, 98, 33))
im.save('_0.png')

하지만 OpenCV에서는 어떻게 해야 하나요?

내가 시도한 건 다음과 같다.

im = cv.imread('0.png', cv.CV_LOAD_IMAGE_GRAYSCALE)
(thresh, im_bw) = cv.threshold(im, 128, 255, cv.THRESH_OTSU)
im = cv.getRectSubPix(im_bw, (98, 33), (1, 1))
cv.imshow('Img', im)
cv.waitKey(0)

하지만 효과가 없어요.

쓴 것 요.getRectSubPix이 경우 이 기능을 올바르게 사용할 수 있는 방법을 알려주세요.

아주 간단해요.Numpy 슬라이스를 사용하세요.

import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)

저는 이 질문을 했고 여기서 또 다른 답을 찾았습니다: 관심 영역 복사

(0)이라는 이름의 로 (0,0imx1,정점으로, (x2 이미지 내에서 직사각형 (x1,y1)는 다음과 같이 됩니다.

roi = im[y1:y2, x1:x2]

여기에서는 이미지의 일부를 잘라내는 등의 정보를 얻을 수 있는 numpy 어레이 인덱싱슬라이싱에 대한 포괄적인 리소스를 제공합니다.이미지는 opencv2에 numpy 배열로 저장됩니다.

:)

이 코드는 x=0,y=0에서 h=100,w=200까지의 이미지를 잘라냅니다.

import numpy as np
import cv2

image = cv2.imread('download.jpg')
y=0
x=0
h=100
w=200
crop = image[y:y+h, x:x+w]
cv2.imshow('Image', crop)
cv2.waitKey(0) 

에서는, 「」의되는 것은 cropped image, 「」, 「」를 합니다.pointerroi이미지를 너무 많이 로드하여 슬라이스로 이미지의 관련 부분을 잘라내고 목록에 추가하는 경우 메모리 낭비가 클 수 있습니다.

를 각각 N개씩 합니다.>1MP은 '만'뿐입니다.100x100왼쪽 상단 모서리에서 영역을 선택합니다.

Slicing:

X = []
for i in range(N):
    im = imread('image_i')
    X.append(im[0:100,0:100]) # This will keep all N images in the memory. 
                              # Because they are still used.

하다'로 부분을 복사할 수도 ..copy() 「가비지 콜렉터」를 합니다.im.

X = []
for i in range(N):
    im = imread('image_i')
    X.append(im[0:100,0:100].copy()) # This will keep only the crops in the memory. 
                                     # im's will be deleted by gc.

이것을 알게 된 후, 유저 1270710코멘트하나가 그것을 언급하고 있는 것을 깨달았습니다만, 그것을 알아내는 데 꽤 시간이 걸렸습니다(디버깅 등).그래서 언급할 가치가 있다고 생각합니다.

opencv 복사 테두리 기능이 있는 견고한 자르기:

def imcrop(img, bbox):
   x1, y1, x2, y2 = bbox
   if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:
        img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)
   return img[y1:y2, x1:x2, :]

def pad_img_to_fit_bbox(img, x1, x2, y1, y2):
    img = cv2.copyMakeBorder(img, - min(0, y1), max(y2 - img.shape[0], 0),
                            -min(0, x1), max(x2 - img.shape[1], 0),cv2.BORDER_REPLICATE)
   y2 += -min(0, y1)
   y1 += -min(0, y1)
   x2 += -min(0, x1)
   x1 += -min(0, x1)
   return img, x1, x2, y1, y2

이미지를 잘라내는 방법은 다음과 같습니다.

image_path:편집할 이미지의 경로

좌표: x/y 좌표 튜플(x1, y1, x2, y2) [이미지를 mspaint로 열고 뷰 탭의 "룰러"를 체크하여 좌표를 확인합니다]

saved_location: 잘라낸 이미지를 저장하는 경로

from PIL import Image
    def crop(image_path, coords, saved_location:
        image_obj = Image.open("Path of the image to be cropped")
            cropped_image = image_obj.crop(coords)
            cropped_image.save(saved_location)
            cropped_image.show()


if __name__ == '__main__':
    image = "image.jpg"
    crop(image, (100, 210, 710,380 ), 'cropped.jpg')

다음은 보다 강력한 imcrop을 위한 코드입니다(matlab과 약간 유사함).

def imcrop(img, bbox): 
    x1,y1,x2,y2 = bbox
    if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:
        img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)
    return img[y1:y2, x1:x2, :]

def pad_img_to_fit_bbox(img, x1, x2, y1, y2):
    img = np.pad(img, ((np.abs(np.minimum(0, y1)), np.maximum(y2 - img.shape[0], 0)),
               (np.abs(np.minimum(0, x1)), np.maximum(x2 - img.shape[1], 0)), (0,0)), mode="constant")
    y1 += np.abs(np.minimum(0, y1))
    y2 += np.abs(np.minimum(0, y1))
    x1 += np.abs(np.minimum(0, x1))
    x2 += np.abs(np.minimum(0, x1))
    return img, x1, x2, y1, y2

또는 잘라내기에는 텐서플로우를 사용하고 영상에서 배열을 만들기 위해 openCV를 사용할 수 있습니다.

import cv2
img = cv2.imread('YOURIMAGE.png')

, 이제img는 (이미지 높이, 이미지 폭, 3)의 형상 배열입니다.텐서플로우를 사용하여 배열을 자릅니다.

import tensorflow as tf
offset_height=0
offset_width=0
target_height=500
target_width=500
x = tf.image.crop_to_bounding_box(
    img, offset_height, offset_width, target_height, target_width
)

tf.keras를 사용하여 이미지를 다시 조립합니다.그러면 정상적으로 동작했는지 확인할 수 있습니다.

tf.keras.preprocessing.image.array_to_img(
    x, data_format=None, scale=True, dtype=None
)

그러면 노트북에 사진이 인쇄됩니다(Google Colab에서 테스트됨).


전체 코드를 합친 경우:

import cv2
img = cv2.imread('YOURIMAGE.png')

import tensorflow as tf
offset_height=0
offset_width=0
target_height=500
target_width=500
x = tf.image.crop_to_bounding_box(
    img, offset_height, offset_width, target_height, target_width
)

tf.keras.preprocessing.image.array_to_img(
    x, data_format=None, scale=True, dtype=None
)

코드 아래에 얼굴 사용을 위해 관심 영역(ROI)을 자르다

import cv2 
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
image=cv2.imread("ronaldo.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
     cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2) 
     roi_image = gray[y:y+h, x:x+w]
cv2.imshow("crop/region of interset image",roi_image) 
cv2.waitKey(0)
cv2.destroyAllWindows()

참조를 위해 확인하다

당신을 쉽게 하기 위해 여기에 내가 사용하는 코드가 있다:

    top=514
    right=430
    height= 40
    width=100
    croped_image = image[top : (top + height) , right: (right + width)]
    plt.imshow(croped_image, cmap="gray")
    plt.show()

이 기능을 사용하면 이미지를 쉽게 잘라낼 수 있습니다.

def cropImage(Image, XY: tuple, WH: tuple, returnGrayscale=False):
    # Extract the x,y and w,h values
    (x, y) = XY
    (w, h) = WH
    # Crop Image with numpy splitting
    crop = Image[y:y + h, x:x + w]
    # Check if returnGrayscale Var is true if is then convert image to grayscale
    if returnGrayscale:
        crop = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
    # Return cropped image
    return crop

도움이 되었으면 좋겠다

# Import packages
import cv2

import numpy as np
img = cv2.imread('skewness.png')
print(img.shape) # Print image shape

cv2.imshow("original", img)

# Cropping an image
cropped_image = img[80:280, 150:330]
 
# Display cropped image
cv2.imshow("cropped", cropped_image)

# Save the cropped image
cv2.imwrite("Cropped Image.jpg", cropped_image)

#The function waitKey waits for a key event infinitely (when \f$\texttt{delay}\leq 0\f$ ) or for delay milliseconds, when it is positive
cv2.waitKey(0)

#The function destroyAllWindows destroys all of the opened HighGUI windows.
cv2.destroyAllWindows()

언급URL : https://stackoverflow.com/questions/15589517/how-to-crop-an-image-in-opencv-using-python

반응형