首页 > 解决方案 > Find Alphabet and Color it to Red with OpenCV Python

问题描述

I have a large image with some alphabets in it and cut out of one alphabet ("A"). I need to find each A in the larger image and color it to red.

Large Image: large image

Alphabet A: Letter A

To solve the problem, I have used the following codes-

import cv2, numpy as np

# read the image and convert into binary
a = cv2.imread('search.png', 0) 
ret,binary_image = cv2.threshold(a,230,255,cv2.THRESH_BINARY_INV)

# create the Structuring element
letter_a = cv2.imread('A.png', 0)
ret,se = cv2.threshold(letter_a,230,255,cv2.THRESH_BINARY_INV)

#erosion and dilation for finding A
erosion = cv2.erode(binary_image , se) 
new_se = cv2.flip(se,0)
dilation = cv2.dilate(erosion, new_se) 
cv2.imwrite('dilation.jpg', dilation )

In this point, I get the following image dilation image

As you can see, I am clearly identifying all the A. However, I need to color those A to red and most importantly, write on the first large image with black letter and white background. Is there any way to do that? Maybe using numpy array write on the first image?

标签: pythonopencv

解决方案


您可以按以下方式解决此问题。
首先,要将主图像中的字母着色为红色,最好将其加载为彩色。创建灰度副本以执行阈值。
然后创建具有主图像尺寸的黑色图像,并将该图像的颜色设置为红色。带有 A 的图像用作掩码以获得红色 A 的图像。然后将这些红色 A 添加到主图像中。*

结果:

在此处输入图像描述

代码:

import cv2, numpy as np

# load the image in color
a = cv2.imread('search.png') 
# create grayscale
a_gray = cv2.cvtColor(a,cv2.COLOR_BGR2GRAY)
ret,binary_image = cv2.threshold(a_gray,230,255,cv2.THRESH_BINARY_INV)

# create the Structuring element
letter_a = cv2.imread('A.png', 0)
ret,se = cv2.threshold(letter_a,230,255,cv2.THRESH_BINARY_INV)

#erosion and dilation for finding A
erosion = cv2.erode(binary_image , se) 
new_se = cv2.flip(se,0)
dilation = cv2.dilate(erosion, new_se) 

# create a red background image
red = np.zeros((a.shape[:3]),dtype=a.dtype)
red[:] = (0,0,255)
# apply the mask with A's to get red A's
red_a = cv2.bitwise_and(red,red,mask=dilation)

# Add the A's to the main image
result = cv2.add(a,red_a)

cv2.imshow('Result', result )
cv2.waitKey(0)
cv2.destroyAllWindows()

*如果字母不是黑色的,则需要额外的步骤,请阅读本教程。但是对于您的图像,这不是必需的。


推荐阅读