【问题标题】:Convert an array of RGB hexadecimal values to OpenCV image in Python在 Python 中将一组 RGB 十六进制值转换为 OpenCV 图像
【发布时间】:2019-02-02 11:44:50
【问题描述】:

在程序的输入中,给定 height 行数,其中有 width 个 RRGGBB 值,其中 RR/GG/BB 是十六进制值RGB 格式的对应颜色。
我需要获取输入并将其转换为 OpenCV 图像,以便我可以使用 OpenCV 库与之交互。我将如何做到这一点?

输入示例: https://drive.google.com/file/d/1XuKRuAiQLUv4rbVxl2xTgqYr_8JQeu63/view?usp=sharing 第一个数字是高度,第二个是宽度,文本文件的其余部分是图像本身。

【问题讨论】:

  • 唉,如果你不表明你自己已经为这个问题付出了任何努力,你就不可能找到太多帮助。您可以编辑您的问题以包含您尝试过的内容吗?

标签: python opencv


【解决方案1】:

这是一种非常低效的图像存储方式,而这也是一种相应低效的解包方式!

#!/usr/bin/env python3

import numpy as np
import re
import cv2

# Read in entire file
with open('in.txt') as f:
   s = f.read()

# Find anything that looks like numbers
l=re.findall(r'[0-9a-f]+',s)

# Determine height and width
height = int(l[0])
width  = int(l[1])

# Create numpy array of BGR triplets
im = np.zeros((height,width,3), dtype=np.uint8) 

i = 2
for row in range (height):
    for col in range(width):
        hex = l[i]
        R = int(hex[0:2],16) 
        G = int(hex[2:4],16) 
        B = int(hex[4:6],16) 
        im[row,col] = (B,G,R)
        i = i+1

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


如果数据文件将来消失,前几行是这样的:

1080 1920
232215 18180b 18170b 18180b 18170a 181609 181708 171708 15160c 14170d
15170d 16170d 16160d 16170d 16170d 16170d 15160d 15160d 17170e 17180f
17180f 18180f 191a11 191a12 1c1c0f 1d1d0f 1e1d0f 1f1e10 1e1e10 1f1f12
202013 202113 212214 242413 242413 242413 242412 242410 242611 272610
272612 262712 262710 282811 27290f 2a2b10 2b2c12 2c2d12 2e3012 303210

关键字:Python、Numpy、OpenCV、解析、十六进制、十六进制、图像、图像处理、正则表达式

【讨论】:

  • 这一切都必须在一个 python 文件中完成。输入图像的高度和宽度,然后是 height 数量的带有像素颜色的线条,这些线条被转换为 OpenCV 图像。
  • 我已编辑问题以显示输入文件的示例。
猜你喜欢
  • 2015-06-21
  • 2020-11-14
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
相关资源
最近更新 更多