首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用python将文本布局颜色更改为白色,将文本更改为黑色?

如何使用python将文本布局颜色更改为白色,将文本更改为黑色?
EN

Stack Overflow用户
提问于 2021-06-01 18:50:03
回答 1查看 94关注 0票数 2

我有这张图片。

我想把所有的彩色标题变成白色,把里面的文字变成黑色。

我在下面尝试使图像完全黑白。

代码语言:javascript
运行
复制
img_grey = cv2.imread('img.jpg', cv2.IMREAD_GRAYSCALE)
thresh = 170
img_binary = cv2.threshold(img_grey, thresh, 250, cv2.THRESH_BINARY)[1]
cv2.imwrite('bw_img.jpg',img_binary) 

现在,这些标题是黑色的,其中的文本是白色的。但我想让文本变黑,标题布局变白。那么,有没有人能帮我?

EN

回答 1

Stack Overflow用户

发布于 2021-06-02 22:30:13

您可以将图像转换为HSV,应用阈值来查找彩色区域,并将带有cv2.THRESH_BINARY_INVcv2.threshold的结果仅复制到彩色区域。

建议解决方案的主要阶段:

  • 从BGR颜色空间转换到HSV颜色空间,并获得饱和度颜色通道。

所有黑色和白色都为零,彩色像素大于零。

  • 将阈值应用于饱和度通道。

  • 在二值化的饱和度通道上查找轮廓。

  • 在黑色背景上将轮廓绘制为白色(255值)以形成蒙版。

  • 应用形态闭合来闭合一些黑色间隙。

H113仅从img_binary_inv获取蒙版内的区域(使用cv2.THRESH_BINARY_INV).

  • Copy masked D18到img_grey的结果仅以蒙版为白色的像素表示。

完整的代码示例:

代码语言:javascript
运行
复制
import numpy as np
import cv2

img_bgr = cv2.imread('img.jpg')  # Read image as BGR

img_grey = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)  # Convert from BGR to grayscale.

thresh = 170
img_binary_inv = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY_INV)[1]  # Apply threshold and invert black/white

# Convert from BGR to HSV color space.
hsv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)

# Get the saturation color channel - all black and white are zero, and colored pixels are above zero.
s = hsv[:, :, 1]

thresh = 100
s_binary = cv2.threshold(s, thresh, 255, cv2.THRESH_BINARY)[1]  # Apply threshold to the saturation channel.

# Find contours on s_binary
cnts = cv2.findContours(s_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2]  # Use index [-2] to be compatible to OpenCV 3 and 4

# Draw the contours as white (255 values) on black background.
mask = np.zeros_like(s_binary)
cv2.drawContours(mask, cnts, -1, 255, -1)

# Apply morphological closing for closing some black gaps.
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((3, 3)))

# Get only the area inside the mask from img_binary_inv
masked_binary_inv = cv2.bitwise_or(img_binary_inv, img_binary_inv, mask=mask)

# Copy masked_binary_inv to img_grey only in pixels that mask is white.
cv2.copyTo(masked_binary_inv, mask, img_grey)

cv2.imwrite('img_grey.png', img_grey)  # Save result (as PNG and not JPEG for better quality).

# Show images
cv2.imshow('img_bgr', img_bgr)
cv2.imshow('s_binary', s_binary)
cv2.imshow('mask', mask)
cv2.imshow('masked_binary_inv', masked_binary_inv)
cv2.imshow('img_grey', img_grey)
cv2.waitKey()
cv2.destroyAllWindows()

结果(img_grey):

由于输入图像的质量相对较低,结果看起来并不是很好。

中间结果:

s_binary

mask

masked_binary_inv

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67787475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档