OCR을 통해서 글자를 추출해야 하는데 뒤의 배경 때문에 인식률이 떨어졌고, 이미지 차이를 구할 필요가 있었다. 이 경우 외에도 필요한 경우가 많이 있어서 작성해본다.


우선, 파이썬(현재 3.8.2)을 설치하고 PIL,numpy 라이브러리를 설치해야한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # main.py from PIL import Image import numpy background_np = numpy.array(Image.open(‘background.png’)) target_np = numpy.array(Image.open(‘target.png’)) diff_np = background_np – target_np for i in range(0,len(diff_np)): for j in range(0,len(diff_np[i])): if not numpy.array_equal(numpy.array([0, 0, 0]),diff_np[i][j]): diff_np[i][j] = target_np[i][j] img = Image.fromarray(diff_np, ‘RGB’) img.save(‘result.png’) img.show() | cs |
main.py 파일을 만들고 같은 디렉토리에 background.png, target.png을 두고 python main.py를 하면 result.png가 저장된다.

두 개의 이미지의 픽셀 rgb값들이 같지 않은 경우 target이미지의 픽셀로 남긴다.
기존 라이브러리 중 이와 비슷한 작업을 할수 있는 라이브러리가 있다. (ImageChops.difference)
이미지 rgb의 차이값을 구하는건 있는데, 공통되지 않은 부분도 빼기 때문에 문제가 생긴다.
1 2 3 4 5 6 7 8 9 10 11 | # test.py from PIL import Image from PIL import ImageChops background_img = Image.open(‘background.png’) target_img = Image.open(‘target.png’) img = ImageChops.difference(target_img, background_img) img.save(‘result2.png’) img.show() | cs |

얼핏보면 첫번째 이미지 결과와 비슷해보이나 전체픽셀에 대해 빼기 때문에 rgb값들이 균일하지가 않다.
워드프레스에 올린 이미지로 하니 이상해서 원본 파일 올려본다.