Python 자습서: Python을 사용한 이미지 처리(OpenCV 사용)

문제를 제거하기 위해 도구를 사용해보십시오

Python 자습서: Python을 사용한 이미지 처리(OpenCV 사용)

이 자습서에서는 OpenCV 라이브러리를 사용하여 Python에서 이미지를 처리하는 방법을 배웁니다.

OpenCV는 실시간 이미지 처리에 사용되는 무료 오픈 소스 라이브러리입니다. 이미지, 비디오 및 라이브 스트림을 처리하는 데 사용되지만 이 자습서에서는 첫 번째 단계로만 이미지를 처리합니다. 시작하기 전에 OpenCV를 설치합시다.

목차



  • OpenCV 설치
  • 이미지 회전
  • 이미지 자르기
  • 이미지 크기 조정
  • 이미지 대비 조정
  • 이미지를 흐리게 만들기
  • 가장자리 감지
  • 이미지를 회색조로 변환(흑백)
  • 중심(블롭 중심) 감지
  • 컬러 이미지에 마스크 적용
  • 이미지에서 텍스트 추출(OCR)
  • 텍스트 기울어짐 감지 및 수정
  • 색상 감지
  • 소음을 줄이다
  • 이미지 윤곽 가져오기
  • 이미지에서 배경 제거

OpenCV 설치

시스템에 OpenCV를 설치하려면 다음 pip 명령을 실행하십시오.

pip install opencv-python

이제 OpenCV가 성공적으로 설치되었으며 준비가 되었습니다. 이미지와 함께 재미를 느껴보자!

이미지 회전

먼저 cv2 모듈을 가져옵니다.

import cv2

이제 이미지를 읽으려면 cv2 모듈의 imread() 메서드를 사용하고 인수에 이미지 경로를 지정하고 이미지를 아래와 같이 변수에 저장합니다.

img = cv2.imread('pyimg.jpg'>NumPy array ! That why image processing using OpenCV is so easy. All the time you are working with a NumPy array.

To display the image, you can use the imshow() method of cv2.

cv2.imshow('Original Image', img) cv2.waitKey(0) 

waitkey 함수는 창이 닫히기 위한 지연으로 밀리초 단위의 인수로 시간이 걸립니다. 여기서 수동으로 창을 닫을 때까지 창을 영원히 표시하기 위해 시간을 0으로 설정합니다.

이 이미지를 회전하려면 나중에 보게 될 회전 과정에서 사용할 이미지의 너비와 높이가 필요합니다.

height, width = img.shape[0:2]

shape 속성은 이미지 행렬의 높이와 너비를 반환합니다. 인쇄하면 |_+_| , 다음과 같은 출력이 표시됩니다.

자, 이제 이미지 행렬이 생겼고 회전 행렬을 얻고 싶습니다. 회전 행렬을 얻으려면 다음을 사용합니다. getRotationMatrix2D() cv2의 방법. 구문 getRotationMatrix2D() 이다:

img.shape[0:2]

여기 센터 는 회전의 중심점이며, 각도 는 각도이며 규모 이미지를 화면에 맞게 만드는 scale 속성입니다.

이미지의 회전 행렬을 얻으려면 코드는 다음과 같습니다.

cv2.getRotationMatrix2D(center, angle, scale)

다음 단계는 회전 행렬의 도움으로 이미지를 회전하는 것입니다.

이미지를 회전하기 위해 cv2 메소드가 있습니다. 랩아핀 원본 이미지, 이미지의 회전 행렬 및 이미지의 너비와 높이를 인수로 사용합니다.

rotationMatrix = cv2.getRotationMatrix2D((width/2, height/2), 90, .5)

회전된 이미지는 rotatedImage 행렬에 저장됩니다. 이미지를 표시하려면 아래와 같이 imshow()를 사용합니다.

rotatedImage = cv2.warpAffine(img, rotationMatrix, (width, height))

위의 코드 줄을 실행하면 다음과 같은 출력이 표시됩니다.

이미지 자르기

먼저 cv2 모듈을 가져와서 이미지를 읽고 이미지의 너비와 높이를 추출해야 합니다.

cv2.imshow('Rotated Image', rotatedImage) cv2.waitKey(0)

우리는 550개의 열(너비)과 350개의 행(높이)을 원한다고 말합니다.

결과는 다음과 같습니다.

이미지 대비 조정

Python OpenCV 모듈에는 이미지 대비를 조정하는 특별한 기능이 없지만 공식 문서 OpenCV의 에서는 이미지 밝기와 이미지 대비를 동시에 수행할 수 있는 방정식을 제안합니다.

import cv2 img = cv2.imread('pyimg.jpg'>

Resize an Image

To resize an image, you can use the resize() method of openCV. In the resize method, you can either specify the values of x and y axis or the number of rows and columns which tells the size of the image.

Import and read the image:

import cv2 img = cv2.imread('pyimg.jpg'>

Now using the row and column values to resize the image:

newImg = cv2.resize(img, (550, 350)) cv2.imshow('Resized Image', newImg) cv2.waitKey(0) 

여기에 이미지의 대비를 정의하는 알파가 있습니다. 1보다 크면 대비가 더 높아집니다.

의 값이 0과 1 사이(1보다 작으나 0보다 큼)이면 대비가 낮아집니다. 1이면 이미지에 대비 효과가 없습니다.

b는 베타를 나타냅니다. b의 값은 -127에서 +127까지 다양합니다.

Python OpenCV에서 이 방정식을 구현하려면 addWeighted() 메서드를 사용할 수 있습니다. 24비트 컬러 이미지에 대해 0과 255 범위의 출력을 생성하므로 addWeighted() 메서드를 사용합니다.

addWeighted() 메서드의 구문은 다음과 같습니다.

new_img = a * original_img + b

이 구문은 가중치가 alpha1인 첫 번째 소스 이미지(source_img1)와 두 번째 소스 이미지(source_img2)의 두 이미지를 혼합합니다.

한 이미지에만 대비를 적용하려면 NumPy를 사용하여 두 번째 이미지 소스를 0으로 추가할 수 있습니다.

간단한 예를 들어 보겠습니다. 다음 모듈을 가져옵니다.

cv2.addWeighted(source_img1, alpha1, source_img2, alpha2, beta)

원본 이미지 읽기:

import cv2 import numpy as np

여기서 minVal 및 maxVal은 각각 최소 및 최대 강도 기울기 값입니다.

다음 코드를 고려하십시오.

img = cv2.imread('pyimg.jpg'>

Make an image blurry

Gaussian Blur

To make an image blurry, you can use the GaussianBlur() method of OpenCV.

The GaussianBlur() uses the Gaussian kernel. The height and width of the kernel should be a positive and an odd number.

Then you have to specify the X and Y direction that is sigmaX and sigmaY respectively. If only one is specified, both are considered the same.

Consider the following example:

import cv2 img = cv2.imread('pyimg.jpg'>

Median Blur

In median blurring, the median of all the pixels of the image is calculated inside the kernel area. The central value is then replaced with the resultant median value. Median blurring is used when there are salt and pepper noise in the image.

To apply median blurring, you can use the medianBlur() method of OpenCV.

Consider the following example where we have a salt and pepper noise in the image:

import cv2 img = cv2.imread('pynoise.png'>

Another comparison of the original image and after blurring:

Detect Edges

To detect the edges in an image, you can use the Canny() method of cv2 which implements the Canny edge detector. The Canny edge detector is also known as the optimal detector .

The syntax to Canny() is as follows:

 cv2.Canny(image, minVal, maxVal) 

이 방정식(xcenter, ycenter)은 원의 중심이고 r은 원의 반지름입니다.

원본 이미지는 다음과 같습니다.

이미지에서 원을 감지한 후 결과는 다음과 같습니다.

자, 이미지에 원이 있고 마스크를 적용할 수 있습니다. 다음 코드를 고려하십시오.

import cv2 img = cv2.imread('pyimg.jpg'>

system.pause C++

Here is the result of the above code on another image:

Convert image to grayscale (Black & White)

The easy way to convert an image in grayscale is to load it like this:

 img = cv2.imread('pyimg.jpg'>

Centroid (Center of blob) detection

To find the center of an image, the first step is to convert the original image into grayscale. We can use the cvtColor() method of cv2 as we did before.

This is demonstrated in the following code:

어디에서 수의사 암호를 살 수 있습니까?
import cv2 img = cv2.imread('py.jpg'>

After detecting the center, our image will be as follows:

Apply a mask for a colored image

Image masking means to apply some other image as a mask on the original image or to change the pixel values in the image.

To apply a mask on the image, we will use the HoughCircles() method of the OpenCV module. The HoughCircles() method detects the circles in an image. After detecting the circles, we can simply apply a mask on these circles.

The HoughCircles() method takes the original image, the Hough Gradient (which detects the gradient information in the edges of the circle), and the information from the following circle equation:

 (x - xcenter)2 + (y - ycenter)2 = r2 

마스크를 만들려면 np.full을 사용하여 주어진 모양의 NumPy 배열을 반환합니다.

import cv2 import numpy as np img1 = cv2.imread('pyimg.jpg'>OpenCV: Hough Circle Transform :

gray_img = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 3) circles = cv2.HoughCircles(gray_img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0) circles = np.uint16(np.around(circles)) 

다음 단계는 다음을 사용하여 생성한 이미지와 마스킹 배열을 결합하는 것입니다. bitwise_or 연산자는 다음과 같습니다.

masking=np.full((img1.shape[0], img1.shape[1]),0,dtype=np.uint8) for j in circles[0, :]: cv2.circle(masking, (j[0], j[1]), j[2], (255, 255, 255), -1)

결과 이미지 표시:

이미지에서 텍스트 추출(OCR)

이미지에서 텍스트를 추출하려면 Google Tesseract-OCR을 사용할 수 있습니다. 여기에서 다운로드할 수 있습니다. 링크

그런 다음 Tesseract-OCR용 Python 래퍼인 pytesseract 모듈을 설치해야 합니다.

텍스트를 추출할 이미지는 다음과 같습니다.

이제 이 이미지의 텍스트를 문자열로 변환하고 텍스트를 출력에 문자열로 표시해 보겠습니다.

pytesseract 모듈을 가져옵니다.

final_img = cv2.bitwise_or(img1, img1, masking=masking)

Tesseract-OCR 실행 파일의 경로를 설정합니다.

import pytesseract

이제 사용 image_to_string 이미지를 문자열로 변환하는 방법:

pytesseract.pytesseract.tesseract_cmd = r'C:Program Files (x86)Tesseract-OCR esseract'

이미지를 읽고 cvtColor()를 사용하여 HSV로 변환합니다.

print(pytesseract.image_to_string('pytext.png'>

Works like charm!

Detect and correct text skew

In this section, we will correct the text skew.

The original image is as follows:

Import the modules cv2, NumPy and read the image:

import cv2 import numpy as np img = cv2.imread('pytext1.png'>

Color Detection

Let’s detect the green color from an image:

Import the modules cv2 for images and NumPy for image arrays:

import cv2 import numpy as np 

cv2의 inRange() 메서드를 사용하여 주어진 이미지 배열 요소가 상위 경계와 하위 경계의 배열 값 사이에 있는지 확인합니다.

img = cv2.imread('pydetect.png'>

Now create a NumPy array for the lower green values and the upper green values:

lower_green = np.array([34, 177, 76]) upper_green = np.array([255, 255, 255]) 

이것은 녹색을 감지합니다.

마지막으로 원본 이미지와 결과 이미지를 표시합니다.

masking = cv2.inRange(hsv_img, lower_green, upper_green)

cv2.imshow('Original Image', img)

소음을 줄이다

이미지의 노이즈를 줄이기 위해 OpenCV는 다음과 같은 방법을 제공합니다.

  1. fastNlMeansDenoising(): 회색조 이미지에서 노이즈를 제거합니다.
  2. fastNlMeansDenoisingColored(): 컬러 이미지에서 노이즈를 제거합니다.
  3. fastNlMeansDenoisingMulti(): 회색조 이미지 프레임(회색조 비디오)에서 노이즈를 제거합니다.
  4. fastNlMeansDenoisingColoredMulti(): 3과 동일하지만 컬러 프레임에서 작동합니다.

이 예에서 fastNlMeansDenoisingColored()를 사용하겠습니다.

cv2 모듈을 가져오고 이미지를 읽습니다.

cv2.imshow('Green Color detection', masking) cv2.waitKey(0)

이미지를 읽고 회색조 이미지로 변환합니다.

2 3 import cv2 img = cv2.imread('pyn1.png'>

Get image contour

Contours are the curves in an image that are joint together. The curves join the continuous points in an image. The purpose of contours is used to detect the objects.

The original image of which we are getting the contours of is given below:

Consider the following code where we used the findContours() method to find the contours in the image:

Import cv2 module:

 import cv2 

이미지를 읽고 이미지를 회색조 이미지로 변환합니다.

img = cv2.imread('py1.jpg'>

Remove Background from an image

To remove the background from an image, we will find the contours to detect edges of the main object and create a mask with np.zeros for the background and then combine the mask and the image using the bitwise_and operator.

Consider the example below:

Import the modules (NumPy and cv2):

import cv2 import numpy as np 

등고선 정렬:

img = cv2.imread('py.jpg'>OpenCV threshold .

Find the image contours:

 img_contours = cv2.findContours(threshed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2] 

np.zeros를 사용하여 마스크 생성:

img_contours = sorted(img_contours, key=cv2.contourArea) for i in img_contours: if cv2.contourArea(i) > 100: break

윤곽 그리기:

mask = np.zeros(img.shape[:2], np.uint8)

bitwise_and 연산자를 적용합니다.

cv2.drawContours(mask, [i],-1, 255, -1)

원본 이미지 표시:

new_img = cv2.bitwise_and(img, img, mask=mask)

결과 이미지 표시:

cv2.imshow('Original Image', img)

보시는 것처럼 OpenCV를 사용하면 이미지 처리가 재미있습니다. 튜토리얼이 유용하기를 바랍니다. 계속 돌아오세요.

감사합니다.

#python #opencv #기계 학습 #인공 지능 #개발자

또한보십시오: