You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化图像傅里叶分量混合函数的条件判断,仅保留两个if?

简化傅里叶分量图像混合函数的条件判断

我正在开发一个图像混合函数,接收两个比例参数与两个傅里叶分量选项(幅值Magnitude、相位Phase、实部Real、虚部Imaginary)。当输入为幅值和相位时,混合规则为:

  • 新幅值 = ratio1*图像1的幅值 + (1-ratio1)*图像2的幅值
  • 新相位 = ratio2*图像2的相位 + (1-ratio2)*图像1的相位

当前实现的函数存在大量冗余条件判断,希望将条件语句简化为仅两个if分支。以下是现有代码:

@staticmethod
def Mix_Images(img_1: 'Images', img_2: 'Images', component_image_1: str, component_image_2: str, Mix_ratio_1: float, Mix_ratio_2: float):
    """
    Mixes two images by combining their Fourier domain components based on user-specified ratios and components.

    Parameters:
    img_1 (Images): The first image object.
    img_2 (Images): The second image object.
    component_image_1 (str): The component of the first image to use in mixing.
    component_image_2 (str): The component of the second image to use in mixing.
    Mix_ratio_1 (float): The ratio of component_image_1 to mix.
    Mix_ratio_2 (float): The ratio of component_image_2 to mix.

    Returns:
    Mixed_img (np.ndarray): The mixed image as a numpy array.
    """

    # Get Fourier parameters for each image
    Fourier_components = {
        "Magnitude": [img_1.get_component("Magnitude"), img_2.get_component("Magnitude")],
        "Phase": [img_1.get_component("Phase"), img_2.get_component("Phase")],
        "Real": [img_1.get_component("Real"), img_2.get_component("Real")],
        "Imaginary": [img_1.get_component("Imaginary"), img_2.get_component("Imaginary")],
        "Uniform phase": [img_1.get_component("Uniform phase"), img_2.get_component("Uniform phase")],
        "Uniform magnitude": [img_1.get_component("Uniform magnitude"), img_2.get_component("Uniform magnitude")]
    }

    Mix_ratio_1 = Mix_ratio_1 / 100
    Mix_ratio_2 = Mix_ratio_2 / 100

    # Mix the components based on user-specified ratios and components
    if component_image_1 in ["Real"] and component_image_2 in ["Imaginary"]:
        New_real = Fourier_components[component_image_1][0] * Mix_ratio_1 + Fourier_components[component_image_1][1] * (1 - Mix_ratio_1)
        New_Imag = Fourier_components[component_image_2][1] * Mix_ratio_2 + Fourier_components[component_image_2][0] * (1 - Mix_ratio_2)
        Mixed_FT = New_real + 1j * New_Imag
        logger.info(f"Component 1: {component_image_1} and Component 2: {component_image_2} have been selected.")

    elif component_image_1 in ["Imaginary"] and component_image_2 in ["Real"]:
        New_Imag = Fourier_components[component_image_1][0] * Mix_ratio_1 + Fourier_components[component_image_1][1] * (1-Mix_ratio_1)
        New_real = Fourier_components[component_image_2][1] * Mix_ratio_2 + Fourier_components[component_image_2][0] * (1 - Mix_ratio_2)
        Mixed_FT = New_real + 1j * New_Imag
        logger.info(f"Component 1: {component_image_1} and Component 2: {component_image_2} have been selected.")

    elif component_image_1 in ["Magnitude", "Uniform magnitude"] and component_image_2 in ["Phase", "Uniform phase"]:
        Mixed_Mag = Fourier_components[component_image_1][0] * Mix_ratio_1 + Fourier_components["Magnitude"][1] * (1 - Mix_ratio_1)
        Mixed_Phase = Fourier_components[component_image_2][1] * Mix_ratio_2 + Fourier_components["Phase"][0] * (1 - Mix_ratio_2)
        Mixed_FT = np.multiply(Mixed_Mag, np.exp(1j * Mixed_Phase))
        logger.info(f"Component 1: {component_image_1} and Component 2: {component_image_2} have been selected.")
    
    elif component_image_1 in ["Phase", "Uniform phase"] and component_image_2 in ["Magnitude", "Uniform magnitude"]:
        Mixed_Mag = Fourier_components[component_image_2][1] * Mix_ratio_2 + Fourier_components["Magnitude"][0] * (1 - Mix_ratio_2)
        Mixed_Phase = Fourier_components[component_image_1][0] * Mix_ratio_1 + Fourier_components["Phase"][1] * (1 - Mix_ratio_1)
        Mixed_FT = np.multiply(Mixed_Mag, np.exp(1j * Mixed_Phase))
        logger.info(f"Component 1: {component_image_1} and Component 2: {component_image_2} have been selected.")

    else:
        st.warning("Invalid Combination")
        logger.warning("Invalid Combination")
        return None

    Image_combined = Images.inverse_fourier_image(Mixed_FT)
    Image_combined = cv2.normalize(Image_combined, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)
    logger.info("Image combined successfully")
    return Image_combined

优化思路

核心是将输入分量归类为两组:

  1. 实部/虚部组:Real、Imaginary
  2. 幅值/相位组:Magnitude、Phase、Uniform magnitude、Uniform phase

通过判断两个输入分量的所属组别,仅用两个if分支处理有效组合,其余情况直接判定为无效,同时提取重复计算逻辑减少冗余。

优化后的代码

@staticmethod
def Mix_Images(img_1: 'Images', img_2: 'Images', component_image_1: str, component_image_2: str, Mix_ratio_1: float, Mix_ratio_2: float):
    """
    基于用户指定的比例和傅里叶分量混合两张图像。

    参数:
    img_1 (Images): 第一张图像对象
    img_2 (Images): 第二张图像对象
    component_image_1 (str): 用于混合的第一张图像的分量
    component_image_2 (str): 用于混合的第二张图像的分量
    Mix_ratio_1 (float): 第一张图像分量的混合比例
    Mix_ratio_2 (float): 第二张图像分量的混合比例

    返回:
    Mixed_img (np.ndarray): 混合后的图像数组
    """
    # 获取各图像的傅里叶分量
    Fourier_components = {
        "Magnitude": [img_1.get_component("Magnitude"), img_2.get_component("Magnitude")],
        "Phase": [img_1.get_component("Phase"), img_2.get_component("Phase")],
        "Real": [img_1.get_component("Real"), img_2.get_component("Real")],
        "Imaginary": [img_1.get_component("Imaginary"), img_2.get_component("Imaginary")],
        "Uniform phase": [img_1.get_component("Uniform phase"), img_2.get_component("Uniform phase")],
        "Uniform magnitude": [img_1.get_component("Uniform magnitude"), img_2.get_component("Uniform magnitude")]
    }

    # 转换比例为小数
    ratio1 = Mix_ratio_1 / 100
    ratio2 = Mix_ratio_2 / 100

    # 定义分量分组
    real_imag_group = {"Real", "Imaginary"}
    mag_phase_group = {"Magnitude", "Phase", "Uniform magnitude", "Uniform phase"}

    Mixed_FT = None
    # 处理实部/虚部组合
    if component_image_1 in real_imag_group and component_image_2 in real_imag_group and component_image_1 != component_image_2:
        # 确定实部和虚部分量
        real_comp = component_image_1 if component_image_1 == "Real" else component_image_2
        imag_comp = component_image_2 if component_image_1 == "Real" else component_image_1
        # 计算混合后的实部和虚部
        New_real = Fourier_components[real_comp][0] * ratio1 + Fourier_components[real_comp][1] * (1 - ratio1)
        New_Imag = Fourier_components[imag_comp][1] * ratio2 + Fourier_components[imag_comp][0] * (1 - ratio2)
        Mixed_FT = New_real + 1j * New_Imag
        logger.info(f"已选择分量组合:{component_image_1} 和 {component_image_2}")
    
    # 处理幅值/相位组合
    elif component_image_1 in mag_phase_group and component_image_2 in mag_phase_group and component_image_1 != component_image_2:
        # 确定幅值类和相位类分量
        is_comp1_mag = component_image_1 in {"Magnitude", "Uniform magnitude"}
        mag_comp = component_image_1 if is_comp1_mag else component_image_2
        phase_comp = component_image_2 if is_comp1_mag else component_image_1
        # 计算混合后的幅值和相位
        Mixed_Mag = Fourier_components[mag_comp][0] * ratio1 + Fourier_components["Magnitude"][1] * (1 - ratio1)
        Mixed_Phase = Fourier_components[phase_comp][1] * ratio2 + Fourier_components["Phase"][0] * (1 - ratio2)
        Mixed_FT = np.multiply(Mixed_Mag, np.exp(1j * Mixed_Phase))
        logger.info(f"已选择分量组合:{component_image_1} 和 {component_image_2}")
    
    else:
        st.warning("无效的分量组合")
        logger.warning("无效的分量组合")
        return None

    # 逆傅里叶变换并归一化
    Image_combined = Images.inverse_fourier_image(Mixed_FT)
    Image_combined = cv2.normalize(Image_combined, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)
    logger.info("图像混合成功")
    return Image_combined

优化说明

  1. 分组判断:通过集合定义分量组别,一次性完成有效组合的判断,替代多个elif分支。
  2. 统一计算逻辑:在实虚/幅相组合中,先明确对应分量类型,再执行统一的混合计算,消除重复代码块。
  3. 精简日志输出:每个有效分支仅保留一次日志记录,避免冗余信息。

内容的提问来源于stack exchange,提问作者Zyad Sowilam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 18:44:52