import subprocess
import os

import ctypes
import os
import numpy as np
script_dir = os.path.dirname(os.path.abspath(__file__))
image_subtraction = ctypes.CDLL(os.path.join(script_dir,'sub_source/libimage_subtraction.so'))


def call_subtract_images(image_data, template_data):
    """
    Subtracts the template image from the input image by calling a C++ function using ctypes.

    Parameters:
    ----------
    image_data : np.ndarray
        The input image data as a 2D NumPy array (float32).
        
    template_data : np.ndarray
        The template image data as a 2D NumPy array (float32).

    Returns:
    --------
    result_copy : np.ndarray
        The resulting image after subtraction, as a 2D NumPy array.
    """
    # image_data = np.float32(image_data)
    # template_data = np.float32(template_data)
    height_t, width_t = template_data.shape
    height_i, width_i = image_data.shape
    image_ptr = image_data.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
    template_ptr = template_data.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
 
    height_o = max(height_i, height_t)
    width_o = max(width_i, width_t)
    # 调用C++函数
    image_subtraction.sub.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int,ctypes.c_int,ctypes.POINTER(ctypes.c_float),ctypes.c_int, ctypes.c_int]
    image_subtraction.sub.restype = ctypes.POINTER(ctypes.c_float)
    result_ptr = image_subtraction.sub(image_ptr,height_i, width_i, template_ptr, height_t, width_t)
    result_data = np.ctypeslib.as_array(result_ptr, shape=(height_o , width_o))
    result_copy = np.copy(result_data)
    # image_subtraction.free_memory(result_ptr)
    return result_copy