簡體   English   中英

使用OpenCV Python查找字母並將其着色為紅色

[英]Find Alphabet and Color it to Red with OpenCV Python

我有一個大圖像,里面有一些字母和一個字母(“A”)。 我需要在較大的圖像中找到每個A並將其顏色變為紅色。

大圖: 大圖

字母A: 字母A.

為了解決這個問題,我使用了以下代碼 -

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 )

在這一點上,我得到以下圖像 擴張圖像

正如你所看到的,我清楚地識別出所有的A.但是,我需要將A染成紅色,最重要的是,用黑色字母和白色背景寫在第一個大圖像上。 有沒有辦法做到這一點? 也許在第一張圖片上使用numpy數組寫?

您可以按如下方式解決此問題。
首先,要在主圖像中為紅色字母着色,最好將其加載為彩色。 創建灰度副本以執行閾值。
然后創建具有主圖像尺寸的黑色圖像,並將該圖像的顏色設置為紅色。 具有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()

*如果字母不是黑色,則需要額外的步驟,請閱讀本教程 但對於你的形象,這不是必要的。

我使用以下代碼來解決問題 -

import cv2, numpy as np
# read the image and convert into binary
color_image = cv2.imread(r'search.png', 1) 
gray_image = cv2.imread(r'search.png', 0) 
ret,binary_image = cv2.threshold(gray_image,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) 

for i in zip(*np.where(dilation == 255)):
    color_image[i[0], i[1], 0] = 0
    color_image[i[0], i[1], 1] = 0
    color_image[i[0], i[1], 2] = 255

# show and save image
cv2.imwrite('all_a.jpg', color_image)
cv2.imshow('All A',color_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM