程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

如何使用 opencv 对图像应用非均匀拉伸

发布于2023-05-09 21:09     阅读(1383)     评论(0)     点赞(25)     收藏(5)


目前我正在使用下面的代码拍摄图像,其中每列像素代表现实世界中的不同宽度(mm)。想象一个标签缠绕在瓶子上。我的输入图像是您直视瓶子时所看到的(较少视角)。我正在尝试打开该标签,以便展平结果具有精确的 1 像素:1 毫米比率。瓶子也不是圆形的,但我有一个方程式来表示它的曲率。有没有更好的方法来做到这一点,结果始终相同并且去拉伸图像更均匀?

见下图,上面的图片是原始图片,下面是我希望达到的效果。 在此处输入图像描述

下面的等式和曲线为我提供了每列像素的压缩因子,其中第 1741 列的像素代表 0.773802mm 在此处输入图像描述

目前我正在使用下面的概率代码根据压缩因子复制/删除像素列。由于概率性质,给定相同的输入,每个输出都是不同的,拉伸校正并不像我想要的那样均匀。注意:上面的条纹图像不是使用此代码生成的

import random
import cv2
import numpy as np


def regularise_image_stretch(img: cv2.Mat, compensations: np.ndarray) -> cv2.Mat:
    '''apply a non uniform stretch to an image based on an equation that maps column idx
    to compression/stretch needed to make the pixel:mm ratio uniform across all cols

    Args:
        img (cv2.Mat): non uniform image
        compensations (np.ndarray): array of compensations per column idx generated from an equation

    Returns:
        cv2.Mat: an image where every pixel represents 1mm
    '''
    def decision(val: float) -> tuple[str, bool, float]:
        '''Based on the compression factor use a probabistic approach to decide 
        whether to insert a copy of the previous column or to delete a column. 

        Args:
            val (float): compression value

        Returns:
            tuple[str, bool, float]: ("add" || "remove", should be applied, probability)
        '''
        addrem = "rem"
        probability = 1 - val
        if probability > 0:
            addrem = "add"

        probability = abs(probability)

        return (addrem, random.random() < probability, probability)

    modimg = img.copy()

    res = list(map(decision, compensations))
    new_img = []
    previous_col = modimg[:, 0, :]

    # add/replicate columns based on compression factor
    for i, col in enumerate(modimg.transpose(1,0,2)):
        addrem, shouldapply, _ = res[i]
        new_img.append(col)

        if shouldapply:
            if addrem == "add":
                new_img.append(previous_col)
            else:
                new_img.pop(-1)

        previous_col = col

    # as a list is being used above fix image orientation
    new_img = cv2.rotate(np.array(new_img), cv2.ROTATE_90_COUNTERCLOCKWISE)
    new_img = cv2.flip(np.array(new_img), 0)
    new_img = cv2.resize(new_img, (img.shape[1], img.shape[0]))
    return new_img


img = cv2.imread("./stripes.jpg")

new_img = regularise_image_stretch(img, compensations)
cv2.imwrite("./modifiend2.png", np.vstack([new_img, img]))

我真的很感激任何帮助:)


解决方案


暂无回答



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/1973276/58021ece8b36efc0f620/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

25 0
收藏该文
已收藏

评论内容:(最多支持255个字符)