在图像中仅保留红色

2024-10-01 13:34:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过去除噪声来细化图像。图像以红色为主,因此我尝试删除除红色以外的任何其他颜色。。下面是一个图像示例 enter image description here

我已找到此代码,但无法正确使用。如果你愿意回答我,把我当作一个新手,一步一步地学习,因为我需要学习的不仅仅是解决一个问题

import cv2
import numpy as np

# Load image
im = cv2.imread('Output.png')

# Make all perfectly green pixels white
im[np.all(im == (193, 47, 47), axis=-1)] = (0,0,0)

# Save result
cv2.imwrite('result1.png',im)

我只需要保留红色和白色作为背景色

我想细化图像,以便能够使用这样的代码从中提取数字

def getCaptcha(img):
    pytesseract.pytesseract.tesseract_cmd=r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
    img=Image.open(img)
    text=pytesseract.image_to_string(img, lang='eng',config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789')
    return text

print(getCaptcha('red_numerals_thresh.jpg'))
print(getCaptcha('red_numerals_result.jpg'))

Tags: 代码图像imageimportimgpngnpresult
1条回答
网友
1楼 · 发布于 2024-10-01 13:34:20

下面是在Python OpenCV中使用cv2.inRange()实现这一点的一种方法

输入:

enter image description here

import cv2
import numpy as np

# Read image
img = cv2.imread('red_numerals.jpg')

# threshold red
lower = np.array([0, 0, 0])
upper = np.array([40, 40, 255])
thresh = cv2.inRange(img, lower, upper)
    
# Change non-red to white
result = img.copy()
result[thresh != 255] = (255,255,255)

# save results
cv2.imwrite('red_numerals_thresh.jpg', thresh)
cv2.imwrite('red_numerals_result.jpg', result)

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

阈值图像:

enter image description here

结果:

enter image description here

相关问题 更多 >