只保留图像中的红色 python
Keep only red colors in an image python
我正在尝试通过去除噪点来优化图像。该图像以红色为主,所以我试图去除除红色以外的任何其他颜色。这是图像的示例
我找到了这段代码,但无法正常使用。如果您愿意回答,请将我视为新手并逐步进行,因为我不仅需要学习来解决问题
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'))
这是在 Python OpenCV 中使用 cv2.inRange() 执行此操作的一种方法。
输入:
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()
阈值图像:
结果:
我正在尝试通过去除噪点来优化图像。该图像以红色为主,所以我试图去除除红色以外的任何其他颜色。这是图像的示例
我找到了这段代码,但无法正常使用。如果您愿意回答,请将我视为新手并逐步进行,因为我不仅需要学习来解决问题
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'))
这是在 Python OpenCV 中使用 cv2.inRange() 执行此操作的一种方法。
输入:
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()
阈值图像:
结果: