python - 识别图像中的网格并使用图像处理更改其颜色
问题描述
我必须识别此图像中的表格网格并将其更改为 Grimson 红色。我是图像处理的初学者。
img_arr = mpimg.imread("1.jpg")
plt.imshow(img_arr)
grid = img_arr[470:800,42:670,(0,1,2)]
plt.imshow(grid.data)
根据图像尺寸,我能够看到图像的网格部分,但我不知道如何识别网格并更改其颜色。如果有人对此有任何想法,请回复。
解决方案
这是一种方法:
- 将图像转换为灰度和阈值
- 查找轮廓并使用轮廓区域过滤以隔离网格
- 查找水平线和垂直线
- 在图像上画线
这是结果
import cv2
import numpy as np
image = cv2.imread('1.png')
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Detect only grid
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
if area > 10000:
cv2.drawContours(mask, [c], -1, (255,255,255), -1)
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
mask = cv2.bitwise_and(mask, thresh)
# Find horizontal lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (55,1))
detect_horizontal = cv2.morphologyEx(mask, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
cv2.drawContours(image, [c], -1, (0,0,255), 2)
# Find vertical lines
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,25))
detect_vertical = cv2.morphologyEx(mask, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detect_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
cv2.drawContours(image, [c], -1, (0,0,255), 2)
cv2.imshow('thresh', thresh)
cv2.imshow('mask', mask)
cv2.imshow('image', image)
cv2.waitKey()
推荐阅读
- selenium - PayPal Sandbox 找不到密码字段
- javascript - TypeError:无法使用 AngularJS 读取未定义的属性“推送”
- reactjs - 反应导航 tabBarOnPress
- taleo - 如何在 Taleo Connect 客户端中取消请求?
- ios - 重新启动应用程序时上一个屏幕闪烁
- javascript - Cross-fetch - GET returns response with no body
- objective-c - 更新桥接头文件
- ruby-on-rails - 如何发现 Savon 在 Rails 应用程序中使用的 TLSv1.2 加密方法
- dart - 使用 Flutter 的座位图布局
- python - 使用 Stack Overflow 数据集 > 5m 个节点创建 networkx 二分图,需要建议和建议