python - 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:
Alphabet 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
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?
解决方案
您可以按以下方式解决此问题。
首先,要将主图像中的字母着色为红色,最好将其加载为彩色。创建灰度副本以执行阈值。
然后创建具有主图像尺寸的黑色图像,并将该图像的颜色设置为红色。带有 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()
*如果字母不是黑色的,则需要额外的步骤,请阅读本教程。但是对于您的图像,这不是必需的。
推荐阅读
- c# - C#如何创建内存中的视频块
- methods - 具有列表类型的定义方法
- python - 我已经使用列表作为每个键的值制作了一个字典,我想打印不带方括号的值
- android - kotlin-PaymentSessionConfiguration
- swift - @EnvironmentObject 属性在 swiftUI 中无法正常工作
- django - 如何使用基于 Django 函数的视图来更新模型?
- amazon-web-services - 更新多对多关系中的记录 - 单表模式
- python - 运行时Tensorflow重建警告
- cypress - 赛普拉斯:获取包含给定字符串/正则表达式的所有元素
- python - Python Scipy fsolve函数返回等于起点的根