Run a complex function on a non-complex image.

    The image needs to be complex, or have an even number of bands. The input
    can be int, the output is always float or double.
339124
def _run_cmplx(fn, image):
    
    original_format = image.format

    if image.format != 'complex' and image.format != 'dpcomplex':
        if image.bands % 2 != 0:
            raise Error('not an even number of bands')

        if image.format != 'float' and image.format != 'double':
            image = image.cast('float')

        if image.format == 'double':
            new_format = 'dpcomplex'
        else:
            new_format = 'complex'

        image = image.copy(format=new_format, bands=image.bands / 2)

    image = fn(image)

    if original_format != 'complex' and original_format != 'dpcomplex':
        if image.format == 'dpcomplex':
            new_format = 'double'
        else:
            new_format = 'float'

        image = image.copy(format=new_format, bands=image.bands * 2)

    return image
822044
def image_set_clim(zmin=None, zmax=None, axes="gca"):
    
    if axes=="gca": axes=_pylab.gca()

    image = axes.images[0]

    if zmin=='auto': zmin = _n.min(image.get_array())
    if zmax=='auto': zmax = _n.max(image.get_array())

    if zmin==None: zmin = image.get_clim()[0]
    if zmax==None: zmax = image.get_clim()[1]

    image.set_clim(zmin, zmax)

    _pylab.draw()
977833
def array2image(array, nx=0, ny=0):
    
    if nx == 0 or ny == 0:
        n = int(np.sqrt(len(array)))
        if n**2 != len(array):
            raise ValueError("lenght of input array given as %s is not square of integer number!" %(len(array)))
        nx, ny = n, n
    image = array.reshape(int(nx), int(ny))
    return image
1351571
@Override
	public void process(GrayF32 input , GrayU8 output ) {
		imageI2.reshape(input.width,input.height);
		meanImage.reshape(input.width,input.height);
		meanI2.reshape(input.width,input.height);
		tmp.reshape(input.width,input.height);
		imageI2.reshape(input.width,input.height);

		int radius = width.computeI(Math.min(input.width,input.height))/2;

		float NP = (radius*2+1)*(radius*2+1);

		// mean of input image = E[X]
		BlurImageOps.mean(input, meanImage, radius, tmp, work);

		// Compute I^2
		PixelMath.pow2(input, imageI2);

		// Compute local mean of I^2
		BlurImageOps.mean(imageI2, meanI2, radius, tmp, work);

		if( down ) {
			//CONCURRENT_BELOW BoofConcurrency.loopFor(0, input.height, y -> {
			for (int y = 0; y < input.height; y++) {
				int i = y * meanI2.width;
				int indexIn = input.startIndex + y * input.stride;
				int indexOut = output.startIndex + y * output.stride;

				for (int x = 0; x < input.width; x++, i++) {
					float mean = meanImage.data[i];
					float A = meanI2.data[i] - (mean*mean/NP);

					// threshold = mean + k*sqrt( A )
					float threshold = mean + k*(float)Math.sqrt(A);
					output.data[indexOut++] = (byte) (input.data[indexIn++] <= threshold ? 1 : 0);
				}
			}
			//CONCURRENT_ABOVE });
		} else {
			//CONCURRENT_BELOW BoofConcurrency.loopFor(0, input.height, y -> {
			for (int y = 0; y < input.height; y++) {
				int i = y * meanI2.width;
				int indexIn = input.startIndex + y * input.stride;
				int indexOut = output.startIndex + y * output.stride;

				for (int x = 0; x < input.width; x++, i++) {
					float mean = meanImage.data[i];
					float A = meanI2.data[i] - (mean*mean/NP);

					// threshold = mean + k*sqrt( A )
					float threshold = mean + k*(float)Math.sqrt(A);
					output.data[indexOut++] = (byte) (input.data[indexIn++] >= threshold ? 1 : 0);
				}
			}
			//CONCURRENT_ABOVE });
		}
	}
978048
public static void multiplyRealComplex( GrayF realA ,
											ImageInterleaved complexB , ImageInterleaved complexC ) {
		if( complexB instanceof InterleavedF32 ) {
			DiscreteFourierTransformOps.multiplyRealComplex((GrayF32) realA, (InterleavedF32) complexB, (InterleavedF32) complexC);
		} else if( complexB instanceof InterleavedF64 ) {
			DiscreteFourierTransformOps.multiplyRealComplex((GrayF64) realA, (InterleavedF64) complexB, (InterleavedF64) complexC);
		} else {
			throw new IllegalArgumentException("Unknown image type");
		}
	}
1274178
def imageplot(f, str=None, sbpt=None):
    """"""
    # Function to plot images
    if str is None:
        str = ''
    if sbpt is None:
        sbpt = []
    if sbpt != []:
        plt.subplot(sbpt[0], sbpt[1], sbpt[2])
    imgplot = plt.imshow(f, interpolation='nearest')
    imgplot.set_cmap('gray')
    plt.axis('off')
    if str != '':
        plt.title(str)
1259356
def execute(self, eopatch):
        
        feature_type, feature_name = next(self.feature(eopatch))
        data = eopatch[feature_type][feature_name].copy()

        # compute band according to compositing method (e.g. blue, maxNDVI, maxNDWI)
        reference_bands = self._get_reference_band(data)

        # find temporal indices corresponding to pre-defined percentile
        indices = self._get_indices(reference_bands)

        # compute composite image selecting values along temporal dimension corresponding to percentile indices
        composite_image = np.empty((data.shape[1:]), np.float32)
        composite_image[:] = self.no_data_value
        for scene_id, scene in enumerate(data):
            composite_image = np.where(np.dstack([indices]) == scene_id, scene, composite_image)

        eopatch[self.composite_type][self.composite_name] = composite_image

        return eopatch
620709
def __scale_image(image, scale: float):
        
        height, width, _ = image.shape

        width_scaled = int(np.ceil(width * scale))
        height_scaled = int(np.ceil(height * scale))

        im_data = cv2.resize(image, (width_scaled, height_scaled), interpolation=cv2.INTER_AREA)

        # Normalize the image's pixels
        im_data_normalized = (im_data - 127.5) * 0.0078125

        return im_data_normalized
402826
def ssim(x, y, data_range=None, scaled = False, verbose = False):
    
    if not x.shape == y.shape:
        raise ValueError('Input images must have the same dimensions.')

    K1 = 0.01
    K2 = 0.03
    sigma = 1.5
    win_size = 7


    if scaled:
        x = x.astype(np.float32)
        y = y.astype(np.float32)

        # center it first for numerical stability...
        my = np.mean(y)
        mx = np.mean(x)
        y = y - my
        sxy = np.mean(x * y)  # mean(y)=0
        sy = np.std(y)
        a, b = sxy / (sy ** 2 + 1.e-30), mx
        if verbose:
            print("scaling in ssim: y2 = %.2g*y+%.2g" % (a, b-my))
        y = a * y + b

        # my = np.mean(y)
        # y = y - my
        # sxy = np.mean(x * y)  # - np.mean(x) * np.mean(y)
        # sy = np.std(y)
        # sx = np.std(x)
        # mx = np.mean(x)
        # a, b = sx / sy, mx
        # print("scaling in ssim: y2 = %.2g*y+%.2g" % (a, b-my))
        # y = a * y + b
        #

    if np.any((np.asarray(x.shape) - win_size) < 0):
        raise ValueError("win_size exceeds image extent.")

    if data_range is None:
        dmin, dmax = np.amin(x), np.amax(x)
        data_range = dmax - dmin+1.e-10

    x_g = OCLArray.from_array(x.astype(np.float32, copy=False))
    y_g = OCLArray.from_array(y.astype(np.float32, copy=False))

    ndim = x.ndim
    NP = win_size ** ndim
    cov_norm = 1. * NP / (NP - 1)  # sample covariance

    filter_func = uniform_filter
    filter_args = {'size': win_size}

    ux = filter_func(x_g, **filter_args)
    uy = filter_func(y_g, **filter_args)

    # compute (weighted) variances and covariances
    uxx = filter_func(x_g * x_g, **filter_args)
    uyy = filter_func(y_g * y_g, **filter_args)
    uxy = filter_func(x_g * y_g, **filter_args)
    vx = cov_norm * (uxx - ux * ux)
    vy = cov_norm * (uyy - uy * uy)
    vxy = cov_norm * (uxy - ux * uy)


    R = 1. * data_range
    C1 = (K1 * R) ** 2
    C2 = (K2 * R) ** 2

    # save some gpu space by minimizing intermediate buffers

    # A1 = 2. * ux * uy+C1
    A1 = np.float32(2.) * ux
    A1 *= uy
    A1 += np.float32(C1)



    # A2 =  2. * vxy + C2
    # overwrite vxy to save space
    A2 = vxy
    A2 *= np.float32(2.)
    A2 += np.float32(C2)


    # B1 =  ux ** 2 + uy ** 2 + C1
    # overwrite ux to save space
    B1 = ux
    B1 *= ux
    uy *= uy
    B1 += uy
    B1 += np.float32(C1)

    # B2 =  vx + vy + C2
    # overwrite vx to save space
    B2 = vx
    B2 += vy
    B2 += np.float32(C2)

    D = B1
    D *= B2
    S = A1
    S *= A2
    S /= D


    # import time
    # time.sleep(2)
    # return 1

    # to avoid edge effects will ignore filter radius strip around edges
    pad = (win_size - 1) // 2

    ss = tuple(slice(pad, s - pad) for s in x.shape)
    # compute (weighted) mean of ssim
    mssim = S.get()[ss].mean()

    return mssim
901770
def pycomplex(v_str):
    """"""
    assert isinstance(v_str, str)

    if v_str[0] == '(' and v_str[-1] == ')' and len(v_str.split(',')) == 2:
        v_re, v_im = v_str[1:-1].split(',', 1)

        # NOTE: Failed float(str) will raise ValueError
        return complex(pyfloat(v_re), pyfloat(v_im))
    else:
        raise ValueError('{0} must be in complex number form (x, y).'
                         ''.format(v_str))
416609
def pixel(self, func:PixelFunc, *args, **kwargs)->'Image':
        ""
        self.px = func(self.px, *args, **kwargs)
        return self
969310
def _call_numpy(self, x):
        
        assert isinstance(x, np.ndarray)

        if self.halfcomplex:
            return np.fft.rfftn(x, axes=self.axes)
        else:
            if self.sign == '-':
                return np.fft.fftn(x, axes=self.axes)
            else:
                # Need to undo Numpy IFFT scaling
                return (np.prod(np.take(self.domain.shape, self.axes)) *
                        np.fft.ifftn(x, axes=self.axes))
681338
def shiftImage(u, v, t, img, interpolation=cv2.INTER_LANCZOS4):
    '''
    
    '''
    ny,nx = u.shape
    sy, sx = np.mgrid[:float(ny):1,:float(nx):1]
    sx += u*t
    sy += v*t
    return cv2.remap(img.astype(np.float32), 
                    (sx).astype(np.float32),
                    (sy).astype(np.float32), interpolation)
1205442
public void process( T image , GrayF32 intensity ) {
		int maxFeatures = (int)(maxFeaturesFraction*image.width*image.height);
		candidatesLow.reset();
		candidatesHigh.reset();
		this.image = image;

		if( stride != image.stride ) {
			stride = image.stride;
			offsets = DiscretizedCircle.imageOffsets(radius, image.stride);
		}
		helper.setImage(image,offsets);

		for (int y = radius; y < image.height-radius; y++) {
			int indexIntensity = intensity.startIndex + y*intensity.stride + radius;
			int index = image.startIndex + y*image.stride + radius;
			for (int x = radius; x < image.width-radius; x++, index++,indexIntensity++) {

				int result = helper.checkPixel(index);

				if( result < 0 ) {
					intensity.data[indexIntensity] = helper.scoreLower(index);
					candidatesLow.add(x,y);
				} else if( result > 0) {
					intensity.data[indexIntensity] = helper.scoreUpper(index);
					candidatesHigh.add(x,y);
				} else {
					intensity.data[indexIntensity] = 0;
				}
			}
			// check on a per row basis to reduce impact on performance
			if( candidatesLow.size + candidatesHigh.size >= maxFeatures )
				break;
		}
	}
1296443
public static <T extends ImageBase<T>> void abs( T input , T output )
	{
		if( input instanceof ImageGray) {
			if (GrayS8.class == input.getClass()) {
				PixelMath.abs((GrayS8) input, (GrayS8) output);
			} else if (GrayS16.class == input.getClass()) {
				PixelMath.abs((GrayS16) input, (GrayS16) output);
			} else if (GrayS32.class == input.getClass()) {
				PixelMath.abs((GrayS32) input, (GrayS32) output);
			} else if (GrayS64.class == input.getClass()) {
				PixelMath.abs((GrayS64) input, (GrayS64) output);
			} else if (GrayF32.class == input.getClass()) {
				PixelMath.abs((GrayF32) input, (GrayF32) output);
			} else if (GrayF64.class == input.getClass()) {
				PixelMath.abs((GrayF64) input, (GrayF64) output);
			}
			// otherwise assume it is an unsigned image type
		} else if( input instanceof ImageInterleaved ) {
			if (InterleavedS8.class == input.getClass()) {
				PixelMath.abs((InterleavedS8) input, (InterleavedS8) output);
			} else if (InterleavedS16.class == input.getClass()) {
				PixelMath.abs((InterleavedS16) input, (InterleavedS16) output);
			} else if (InterleavedS32.class == input.getClass()) {
				PixelMath.abs((InterleavedS32) input, (InterleavedS32) output);
			} else if (InterleavedS64.class == input.getClass()) {
				PixelMath.abs((InterleavedS64) input, (InterleavedS64) output);
			} else if (InterleavedF32.class == input.getClass()) {
				PixelMath.abs((InterleavedF32) input, (InterleavedF32) output);
			} else if (InterleavedF64.class == input.getClass()) {
				PixelMath.abs((InterleavedF64) input, (InterleavedF64) output);
			}
		} else {
			Planar in = (Planar)input;
			Planar out = (Planar)output;

			for (int i = 0; i < in.getNumBands(); i++) {
				abs(in.getBand(i),out.getBand(i));
			}
		}
	}
842294
def is_complex_floating_dtype(dtype):
    """"""
    dtype = np.dtype(dtype)
    return np.issubsctype(getattr(dtype, 'base', None), np.complexfloating)
222415
def _encode_image(self, np_image):
    """"""
    if np_image.dtype != np.uint8:
      raise ValueError('Image should be uint8. Detected: %s.' % np_image.dtype)
    utils.assert_shape_match(np_image.shape, self._shape)
    return self._runner.run(ENCODE_FN[self._encoding_format], np_image)