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

2024-04-25 00:11:14 发布

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

我有这个图像

this

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

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

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) 

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


Tags: 图像文本标题imgcv2彩色greyjpg
1条回答
网友
1楼 · 发布于 2024-04-25 00:11:14

您可以将图像转换为HSV,应用阈值以查找彩色区域,并将cv2.thresholdcv2.THRESH_BINARY_INV的结果仅复制到彩色区域

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

  • 从BGR转换到HSV颜色空间,获得饱和度颜色通道。
    所有黑色和白色均为零,彩色像素高于零
  • 将阈值应用于饱和通道
  • 在二值化饱和通道上查找轮廓
  • 将轮廓绘制为黑色背景上的白色(255个值)以形成遮罩
  • 应用形态学闭合来闭合一些黑色间隙
  • 仅从img_binary_inv获取掩码内的区域(代码使用cv2.THRESH_BINARY_INV的结果)
  • 仅在遮罩为白色的像素中将遮罩img_binary_inv复制到img_grey

完整的代码示例:

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):
enter image description here
结果看起来不太好,因为输入图像的质量相对较低


中间结果:

s_binary
enter image description here

mask
enter image description here

masked_binary_inv
enter image description here

相关问题 更多 >