コード例 #1
0
ファイル: poc.py プロジェクト: ohtaketakeshi/imageTools
def logpolar(src, center, M):
    srcshape = src.shape[0:2]
    dstshape = (4096, 1024)
    return cv.warpPolar(
        src, dstshape, center, M,
        flags=cv.WARP_POLAR_LOG+cv.INTER_CUBIC+cv.WARP_FILL_OUTLIERS
        )
コード例 #2
0
def check_screen(left, right, extra):
    global checked
    x, y = CENTER
    r = RADIUS
    screen = get_shot(0, x - r, y - r, 2 * r, 2 * r)

    rotated = cv.rotate(screen, cv.ROTATE_90_COUNTERCLOCKWISE)
    circle = cv.warpPolar(rotated, (300, 1000), (r, r), RADIUS,
                          cv.WARP_POLAR_LINEAR)
    circle = cv.rotate(circle, cv.ROTATE_90_COUNTERCLOCKWISE)
    ring = circle[:150]
    if SAVE_SHOTS:
        dt = time.time() - T0
        name = "shots/ring-%s+%s.png" % (T0, dt)
        cv.imwrite(name, ring)
        logger.info("%s Saved.", name)

    diffe, xe = get_match_x(ring, extra)
    checked += 1
    xe += extra[0].shape[2] / 2
    if diffe < 0.2:
        logger.info("Found Extra=%s", xe)
        return xe
    diff0, x0 = get_match_x(ring, left)
    diff1, x1 = get_match_x(ring, right)
    x1 += right[0].shape[1]
    if diff0 > 0.3 or diff1 > 0.3:
        name = "shots/NoMatch-{}+{}.png".format(T0, time.time() - T0)
        cv.imwrite(name, ring)
        logger.warning("Not Valid Match. diff=%s, %s, %s for %s", diffe, diff0,
                       diff1, name)
        return None
    logger.info("Found left=%s, right=%s", x0, x1)
    return (x0 + x1) / 2
コード例 #3
0
def to_log_polar_coords(image):
    flags = cv.INTER_LINEAR + cv.WARP_FILL_OUTLIERS + cv.WARP_POLAR_LOG
    w, h = image.shape[::-1]
    centre = (w / 2, h / 2)
    R = (w - 1) / 2
    log_polar_img = cv.warpPolar(image, (w, h), centre, R, flags)
    return log_polar_img
コード例 #4
0
ファイル: clock_face.py プロジェクト: qucals/clock-detector
    def wrap_polar_face(image,
                        width=config.DEFAULT_WRAP_POLAR_WIDTH,
                        height=config.DEFAULT_WRAP_POLAR_HEIGHT,
                        error_height=config.DEFAULT_WRAP_POLAR_HEIGHT_ERROR):
        """Wraps the clock face up.

        Args:
            image (numpy.ndarray): The clock face image.
            width (int, optional): The width of the final image. Defaults to config.WRAP_POLAR_WIDTH.
            height (int, optional): The height of the final image. Defaults to config.WRAP_POLAR_HEIGHT.
            error_height (int, optional): The error of the height. Defaults to config.DEFAULT_WRAP_POLAR_HEIGHT_ERROR

        Returns:
            numpy.narray: The final wrapped image.
        """

        rotate = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
        centre = rotate.shape[0] // 2

        polarImage = cv2.warpPolar(
            rotate, (height, width), (centre, centre), centre,
            cv2.INTER_CUBIC + cv2.WARP_FILL_OUTLIERS + cv2.WARP_POLAR_LINEAR)

        cropImage = copy.deepcopy(polarImage[0:width, error_height:height])
        cropImage = cv2.rotate(cropImage, cv2.ROTATE_90_COUNTERCLOCKWISE)

        return cropImage
コード例 #5
0
ファイル: NewConvert.py プロジェクト: Tipriest/bbPOV-P
def polarConv(imgOrgin, outputName):
    global gammaCorrection
    h = imgOrgin.shape[0]  #帧尺寸
    w = imgOrgin.shape[1]
    #画像縮小
    imgRedu = cv2.resize(imgOrgin, (math.floor(
        (NUMPIXELS * 2 - 1) / h * w), NUMPIXELS * 2 - 1))
    #顺时针旋转90度 因为下一步的极坐标转换的0度是正东方向,而我们的POV正北方向为0度
    imgRedu = cv2.rotate(imgRedu, cv2.ROTATE_90_CLOCKWISE)
    polar_image = cv2.warpPolar(imgRedu, (NUMPIXELS, Div),
                                (imgRedu.shape[1] / 2, imgRedu.shape[0] / 2),
                                min(imgRedu.shape[0], imgRedu.shape[1]) / 2, 0)
    for i in range(NUMPIXELS):  #亮度处理
        polar_image[:, i, 0] = polar_image[:, i, 0] * (
            (100 - Led0Bright) / NUMPIXELS * i +
            Led0Bright) / 100 * Bright / 100
        polar_image[:, i, 1] = polar_image[:, i, 1] * (
            (100 - Led0Bright) / NUMPIXELS * i +
            Led0Bright) / 100 * Bright / 100
        polar_image[:, i, 2] = polar_image[:, i, 2] * (
            (100 - Led0Bright) / NUMPIXELS * i +
            Led0Bright) / 100 * Bright / 100
    #polar_image[:,i,2] = hsv[:,i,2] * ((100 - Led0Bright) / NUMPIXELS * i + Led0Bright) / 100 * Bright /100
    if (gammaCorrection):
        polar_image = cv2.LUT(polar_image, lut)
    cv2.imwrite(outputName + '.jpg', polar_image,
                [int(cv2.IMWRITE_JPEG_QUALITY), 100] +
                [int(cv2.IMWRITE_JPEG_OPTIMIZE), True])
コード例 #6
0
def to_log_polar_coords(image):
    flags = cv.INTER_LINEAR + cv.WARP_FILL_OUTLIERS + cv.WARP_POLAR_LOG
    w, h = image.shape[::-1]
    centre = (w / 2, h / 2)
    max_radius = np.sqrt((w / 2)**2 + (h / 2)**2)
    log_polar_img = cv.warpPolar(image, (w, h), centre, max_radius, flags)
    #log_polar_img = cv.linearPolar(image, centre, max_radius, flags)
    return log_polar_img
コード例 #7
0
ファイル: Fourier.py プロジェクト: tristaaan/stitch-eval
def log_polar(img):
    '''
    Convert image into log-polar space
    '''
    rad_size = 2.0
    center = (img.shape[0] / 2, img.shape[1] / 2)
    radius = round(sqrt(center[0] ** rad_size + center[1] ** rad_size))
    return cv2.warpPolar(img, img.shape, center, radius, cv2.WARP_POLAR_LOG)
コード例 #8
0
def warp_polar(img, circle):
    warped = cv2.warpPolar(img,
                           dsize=(1000, warped_h),
                           center=(circle[0], circle[1]),
                           maxRadius=circle[2],
                           flags=cv2.WARP_POLAR_LINEAR)
    d_imwrite("warp_polar.jpg", warped)
    return warped
コード例 #9
0
ファイル: crater_detection.py プロジェクト: hugo-rc/stage_m2
 def polar_plot(self,i):
     img=self.build_img(self.files[i])
     img=self.img_processing(img)    
     self.a=self.sym_axis(img)
     #value = np.sqrt(((img.shape[0]/2.0)**2.0)+((img.shape[1]/2.0)**2.0))
     value=img.shape[0]
     polar_image = cv2.warpPolar(img,np.shape(img),(self.a,0), value, cv2.WARP_FILL_OUTLIERS)        
     polar_image = polar_image.astype(np.uint8)
     plt.imshow(polar_image)
     plt.show()
コード例 #10
0
 def get_polar(img, radius, deg, px, py):
     flags = cv2.INTER_LINEAR + cv2.WARP_FILL_OUTLIERS + cv2.WARP_POLAR_LINEAR
     norm = cv2.normalize(img,
                          None,
                          0,
                          255,
                          cv2.NORM_MINMAX,
                          dtype=cv2.CV_8U)
     polar = cv2.warpPolar(norm, (radius, int(360 / deg)), (px, py), radius,
                           flags)
     return polar
コード例 #11
0
ファイル: crater_detection.py プロジェクト: hugo-rc/stage_m2
 def img_processing(self,img,coordinate='Cartesian'):        
     img=self.remove_background(img,self.img_background)
     img=self.crop(img,self.z_surf)
     img=self.threshold(img)     
     a=self.sym_axis(img)
     value=img.shape[0]
     polar_image = cv2.warpPolar(img,np.shape(img),(a,0), value, cv2.WARP_FILL_OUTLIERS)
     if coordinate=='Cartesian':
         return img
     elif coordinate=='Polar':
         l=int(len(polar_image)/2)
         return polar_image[:l,:]
コード例 #12
0
def transform_polar2cartesian(image):
    height, width = image.shape
    c = (
        float(768 / 2.0), float(562 / 2.0)
    )  #Se define el centroide que se usa como referencia para la transformación
    imgRes = cv2.warpPolar(
        image,
        (height, width),
        c,
        260,  #Se realiza el cambio de coordenadas
        cv2.INTER_LINEAR + cv2.WARP_POLAR_LOG)
    imgRes = cv2.addWeighted(
        imgRes, 1.3, np.zeros(imgRes.shape, imgRes.dtype), 0,
        0)  #Se crea una imagen nueva con la transformación realizada
    return (imgRes)  #Se retorna la imagen en coordenadas cartesianas
コード例 #13
0
ファイル: ffts.py プロジェクト: wdwzyyg/AICrystallographer
def raaft(patch, which_norm, inner=0, outer=1):
    """
    Given an image patch and choice of norm, generate the RAAFT feature vector for that patch.

    Parameters
    ----------
    patch : 2D numpy array
        The patch which we want to apply the RAAFT to.
    which_norm : float
        Which norm to normalize the feature vector by. Can choose any real number
        for this value, but choosing 1 <= which_norm <= infty is the most natural.
        Choosing either 1 or 2 works well in most cases.
    inner, outer : float
        To help with noise it is sometimes useful to set parts of the Fourier transform
        of in each patch to zero. If a patch has dimensions (px, py) then the points 
        (kx,ky) in k-space which are not set to zero must satisfy: 
            inner * sqrt(px^2 + py^2) <= sqrt(kx^2 + ky^2) 
            outer * sqrt(px^2 + py^2) >= sqrt(kx^2 + ky^2)

    Returns
    -------
    feat_vector : 2D numpy array with shape (patch.shape[0], 1)
        The RAAFT feature vector corresponding to the given patch.
    """
    p_sz = patch.shape
    center = (p_sz[0] // 2, p_sz[1] // 2)
    rad = np.sqrt((p_sz[0]**2 + p_sz[1]**2) / 2)
    tol = 1e-10  # this so we don't accidentally divide by 0

    #
    #patch = (patch - np.mean(patch)) / np.std(patch)

    # Take the absolute value of the Fourier transform
    tmp_img = np.abs(fftpack.fftshift(cv2.dct(patch)))

    # Normalize the patch
    tmp_img /= norm(np.ndarray.flatten(tmp_img), ord=which_norm) + tol

    # Perform the polar transform
    tmp_img = cv2.warpPolar(tmp_img, None, center, rad,
                            cv2.WARP_FILL_OUTLIERS + cv2.INTER_CUBIC)

    # Sum over the radial variable
    feat_vec = np.sum(tmp_img, 0)
    feat_vec[:int(rad * inner)] = 0
    feat_vec[int(rad * outer):] = 0

    return np.array(feat_vec, ndmin=2)
コード例 #14
0
def create_wedge(size, blur_radius=None):
    wedge = np.zeros((8, 1))
    wedge[1::4] = 1
    wedge[2::4] = 1
    wedge = resize(wedge, size, order=0)
    if blur_radius is not None:
        wedge = cv2.blur(wedge, (1, int(blur_radius / 360 * size[1])))
    wedge = cv2.warpPolar(
        wedge,
        size,
        tuple([s / 2 for s in size]),
        size[0],
        cv2.WARP_INVERSE_MAP,
    )
    wedge[tuple([int(s / 2) for s in size])] = 0.5
    return wedge
コード例 #15
0
def getPolar2CartImg(image, rad):
	c = (float(np.size(image, 0)/2.0), float(np.size(image, 1)/2.0))
	imgRes = cv.warpPolar(image, (rad*3,360), c, np.size(image, 0)/2, cv.WARP_POLAR_LOG)

	for valid_width in reversed(range(rad*3)):
		blank_cnt = 0
		for h in range(360):
			if (imgRes[h][valid_width] != 0):
				blank_cnt+=1
		if(blank_cnt == 0):
			imgRes = imgRes[0:360, valid_width:rad*3]
			break

	imgRes = cv.resize(imgRes, (80, 360), interpolation=cv.INTER_CUBIC)
	

	return imgRes
コード例 #16
0
ファイル: filters.py プロジェクト: pji/pjinoise
    def process(self, a: np.ndarray) -> np.ndarray:
        """ Based on code taken from:
        https://stackoverflow.com/questions/51675940/converting-an-image-from-cartesian-to-polar-limb-darkening
        """
        # cv2.warpPolar only works on two dimensional arrays. If the
        # array is three dimensional, call process recursively with
        # each two-dimensional slice of the three-dimensional array.
        if len(a.shape) == 3:
            for index in range(a.shape[Z]):
                a[index] = self.process(a[index])
            return a

        # Roll the image into polar coordinates.
        center = tuple([n / 2 for n in a.shape])
        max_radius = np.sqrt(sum(n**2 for n in center))
        flags = cv2.WARP_POLAR_LINEAR + cv2.WARP_INVERSE_MAP
        return cv2.warpPolar(a, a.shape, center, max_radius, flags)
コード例 #17
0
def shot():
    x, y = CENTER
    r = RADIUS
    screen = get_shot(0, x - r, y - r, 2 * r, 2 * r)
    logger.info("Screen Capurted")
    cv.imwrite("images/screen.png", screen)

    rotated = cv.rotate(screen, cv.ROTATE_90_COUNTERCLOCKWISE)
    logger.info("Rotate End")
    circle = cv.warpPolar(rotated, (300, 1000), (r, r), RADIUS,
                          cv.WARP_POLAR_LINEAR)
    logger.info("warpPolar End")
    circle = cv.rotate(circle, cv.ROTATE_90_COUNTERCLOCKWISE)
    logger.info("Rotate End")
    ring = circle[:150]
    logger.info("All Transform End")
    cv.imwrite("images/ring.png", ring)
    logger.info("Saved")
コード例 #18
0
    def get_filter(self):
        lidar_range_pix = int(LidarSpec.RANGE * self.XY_resolution)
        filter_size = lidar_range_pix * 2
        poler_filter = np.zeros((self.angle_resolution, lidar_range_pix),
                                dtype=float)
        map_filter = np.zeros(
            (self.angle_resolution, filter_size, filter_size))

        flags = cv2.INTER_CUBIC + cv2.WARP_FILL_OUTLIERS + cv2.WARP_POLAR_LINEAR + cv2.WARP_INVERSE_MAP

        for angle_pix in range(0, self.angle_resolution):
            poler_filter.fill(0.0)
            poler_filter[angle_pix, :] = 1.0

            map_filter[angle_pix] = cv2.warpPolar(
                poler_filter, (filter_size, filter_size),
                (lidar_range_pix, lidar_range_pix), lidar_range_pix, flags)

        return map_filter, filter_size
コード例 #19
0
def estCorrect(orgImg0, cutoffF=0.8, margin=0.1):
    orgImg = cv2.fastNlMeansDenoisingColored(orgImg0, None, 9, 9, 7, 21)
    w = orgImg.shape[1]
    crop_img = orgImg[:, int(margin * w):int(w - margin * w)]
    pix_color = np.array(crop_img)
    full_pix_color = np.array(orgImg)
    img = rgb2gray(pix_color)
    img = abs(img[0:-1, :] - img[1:, :])

    f = np.fft.fft2(img)
    fshift = np.fft.fftshift(f)
    magnitude_spectrum = 20 * np.log(np.abs(fshift))

    #plt.subplot(143),plt.imshow(np.abs(fshift), cmap = 'gray')
    #plt.title('np.abs(fshift)'), plt.xticks([]), plt.yticks([])
    margin = 0.9  # Cut off the outer 10% of the image
    # Do the polar rotation along 100 angular steps with a radius of 256 pixels.
    size = min(img.shape)
    polar_img = cv2.warpPolar(magnitude_spectrum, (int(size / 2), 200),
                              (img.shape[1] / 2, img.shape[0] / 2),
                              size * margin * 0.5, cv2.WARP_POLAR_LINEAR)

    polar_img_lowF = polar_img[:,
                               int(0.01 *
                                   polar_img.shape[1]):int(cutoffF *
                                                           polar_img.shape[1])]

    polar_sum_200 = np.sum(polar_img_lowF, axis=1)
    polar_sum = polar_sum_200[0:100] + polar_sum_200[100:200]
    #polar_sum[50]=min(polar_sum) #matthew  do not count center line
    #print(statistics.stdev(polar_sum[25:75]))
    maxIndex = np.argmax(polar_sum[25:75]) + 25
    offsetDegree = (maxIndex - 50) / 100 * 3.14
    aEst = np.sin(offsetDegree)
    full_pix_color0 = np.array(orgImg0)
    correctImg = imgWrapA(full_pix_color0, aEst)
    #full_pix_color
    #polar_sum[25:75]=min(polar_sum) #matthew  do not count center line
    #maxIndex2=np.argmax(polar_sum)
    #print("maxIndex2={}".format(maxIndex2))

    return correctImg
コード例 #20
0
def polarConv(imgOrgin):
    h = imgOrgin.height #帧尺寸
    w = imgOrgin.width
    #画像縮小
    imgRedu = cv2.resize(np.array(imgOrgin),(math.floor((NUMPIXELS * 2 -1)/h *w), NUMPIXELS * 2 -1))
    #顺时针旋转90度 因为下一步的极坐标转换的0度是正东方向,而我们的POV正北方向为0度
    imgRedu = cv2.rotate(imgRedu,cv2.ROTATE_90_CLOCKWISE)  
    polar_image = cv2.warpPolar(imgRedu,(NUMPIXELS , Div ), (imgRedu.shape[1]/2,imgRedu.shape[0]/2) ,min(imgRedu.shape[0], imgRedu.shape[1]) / 2, 0)
    for i in range(NUMPIXELS):  #亮度处理
         polar_image[:,i,0] = polar_image[:,i,0] * ((100 - Led0Bright) / NUMPIXELS * i + Led0Bright) / 100 * Bright /100
         polar_image[:,i,1] = polar_image[:,i,1] * ((100 - Led0Bright) / NUMPIXELS * i + Led0Bright) / 100 * Bright /100 
         polar_image[:,i,2] = polar_image[:,i,2] * ((100 - Led0Bright) / NUMPIXELS * i + Led0Bright) / 100 * Bright /100 
        #polar_image[:,i,2] = hsv[:,i,2] * ((100 - Led0Bright) / NUMPIXELS * i + Led0Bright) / 100 * Bright /100
    #cv2.imwrite(outputName+'.jpg',polar_image,[int(cv2.IMWRITE_JPEG_OPTIMIZE), True])
    ret,img_encode = cv2.imencode('.jpg',polar_image,[int(cv2.IMWRITE_JPEG_QUALITY), 50]+[int(cv2.IMWRITE_JPEG_OPTIMIZE), True])
    data = np.array(img_encode)
    stringData = data.tobytes()
    print(str(len(stringData)))
    s.send(str.encode(str(len(stringData)).ljust(5)+'\r'));  
    s.sendall(stringData)
コード例 #21
0
def mask_circle_and_wrap_polar(img):
    try:
        x, y, rad = get_center_circle(img)
        if abs(rad -
               settings.SMALL_RADIUS_SIZE) < abs(rad -
                                                 settings.MED_RADIUS_SIZE):
            rad = settings.BIG_RADIUS_SIZE / settings.SMALL_RADIUS_SIZE * rad
        elif abs(rad -
                 settings.MED_RADIUS_SIZE) < abs(rad -
                                                 settings.BIG_RADIUS_SIZE):
            rad = settings.BIG_RADIUS_SIZE / settings.MED_RADIUS_SIZE * rad
    except TypeError:
        x, y = settings.AVERAGE_CENTER
        rad = settings.BIG_RADIUS_SIZE
    dim = settings.OUTPUT_IMG_DIMENSION
    return cv2.warpPolar(
        img,
        (dim, dim),
        (x, y),
        int(settings.CIRCLE_PERC_FILTER * rad),
        cv2.WARP_POLAR_LINEAR,
    )
コード例 #22
0
    def get_Likelihood_function(self, robot_position):
        tuples = [(0, 0)]

        for robot_pix in self.pos_to_pix(robot_position):
            try:
                tuples += [
                    self.pad_tuple(self._filter_size, self.pixels_len,
                                   robot_pix)
                ]
            except ArithmeticError as error:
                print(error)

        print(tuples)
        ajusted_filter = np.pad(self._filter, tuples, constant_values=0)
        print(ajusted_filter.shape)
        likelihood_poler = np.sum(self.data * ajusted_filter, axis=0)

        flags = cv2.INTER_CUBIC + cv2.WARP_FILL_OUTLIERS + cv2.WARP_POLAR_LINEAR + cv2.WARP_INVERSE_MAP
        likelihood = cv2.warpPolar(likelihood_poler,
                                   (self.angle_resolution, self.pixels_len),
                                   (self._origin_pixel, self._origin_pixel),
                                   self.pixels_len, flags)

        return likelihood, likelihood_poler, ajusted_filter
コード例 #23
0
if capture is None:
    print("Video not found.", file=sys.stderr)
    sys.exit(1)

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
output_size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)),
               int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fps = capture.get(cv2.CAP_PROP_FPS)
output = cv2.VideoWriter('logpolar.avi', fourcc, fps, output_size, isColor=1)

captured, frame = capture.read()
key = 0

while captured and key != ENTER:
    width, height = output_size
    logpolar_frame = cv2.warpPolar(
        src=frame,
        dsize=output_size,
        center=(width // 2, height // 2),
        maxRadius=40,
        flags=cv2.INTER_LINEAR + cv2.WARP_FILL_OUTLIERS + cv2.WARP_INVERSE_MAP)
    output.write(logpolar_frame)
    cv2.imshow('video', frame)
    cv2.imshow('Logpolar', logpolar_frame)
    captured, frame = capture.read()
    key = cv2.waitKey(delay=33)

capture.release()
output.release()
cv2.destroyAllWindows()
コード例 #24
0
import cv2
import numpy as np
img = cv2.imread("polar_remap_doc.png")
dst = cv2.warpPolar(img, (176, 1106), (234, 208), 176,
                    cv2.INTER_NEAREST + cv2.WARP_POLAR_LINEAR)
cv2.namedWindow('r', 0)
cv2.resizeWindow('r', 640, 480)
cv2.imshow('r', dst)
cv2.waitKey(0)
cv2.imshow('r', img)
cv2.waitKey(0)
コード例 #25
0
ファイル: radial_profile.py プロジェクト: tsukada-cs/TCSAR
def get_polar(img, radius, deg, px, py):
    flags = cv2.INTER_LINEAR + cv2.WARP_FILL_OUTLIERS + cv2.WARP_POLAR_LINEAR
    polar = cv2.warpPolar(img, (radius, int(360/deg)), (px, py), radius, flags) 
    return polar
コード例 #26
0
import cv2
from skimage.feature import register_translation
import numpy as np
import matplotlib.pyplot as plt

fnames = [
    "/data1/mschroeder/Datasets/18-10-SedimentTrap-Fred/M138 T4 600A/T4 600A 13.jpeg",
    "/data1/mschroeder/Datasets/18-10-SedimentTrap-Fred/M138 T4 600A/T4 600A 3.jpeg"
]

frames = [cv2.imread(fn) for fn in fnames]

frames_pol = []
for f in frames:
    print(f.shape)
    center = f.shape[0] / 2, f.shape[1] / 2
    frames_pol.append(
        cv2.warpPolar(f, (0, 0), center, max(center),
                      cv2.WARP_POLAR_LOG + cv2.WARP_FILL_OUTLIERS))

for f in frames_pol:
    print(f.shape)

# Subpixel-accurate registration
# translation = register_translation(frames_pol[0][...,0], frames_pol[1][...,0])

image_product = np.fft.fft2(frames_pol[0][..., 0]) * np.fft.fft2(
    frames_pol[1][..., 0]).conj()
cc_image = np.fft.fftshift(np.fft.ifft2(image_product))
plt.imshow(cc_image.real)
コード例 #27
0
# pulls a random circle - in theory, this is the only one that should be found, but this isn't always certain depending on noise

trueCenter = None
for i in circles[0]:
    if ((np.abs(i[1] - center[0])**2 + np.abs(i[0] - center[1])**2)**0.5 < 35):
        trueCenter = i
        # draw the outer circle
        cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
        # draw the center of the circle
        cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)

#transform to polar and draw image - do this twice, once for the image to display,
#and once for the one to do the math on (which should not have debug graphics - eg the center of the circle drawn)
size = int(np.shape(img)[0] / 2)
dst = cv2.warpPolar(cimg, (size, size), (trueCenter[0], trueCenter[1]),
                    maxRadius=size,
                    flags=cv2.WARP_POLAR_LINEAR)
dst2 = cv2.warpPolar(bwimg, (size, size), (trueCenter[0], trueCenter[1]),
                     maxRadius=size,
                     flags=cv2.WARP_POLAR_LINEAR)

#plot intensities and figures
fig = plt.figure()

plt.subplot(2, 2, 1)
plt.imshow(cimg)

plt.subplot(2, 2, 2)
#plot pixel intensities from center to the side of the image (bad way)
plt.plot(
    range(0, len(bwimg[trueCenter[1]]))[trueCenter[0]:],
コード例 #28
0
ファイル: clockread.py プロジェクト: AdamV98/ClockRead
        center = (0, 0)
        radius = 0

        #***************Az ora körvonalanak megkeresese*************************************

        if circles is not None:
            circles = np.uint16(np.around(circles))
            for i in circles[0, :]:
                center = (i[0], i[1])
                cv2.circle(src, center, 1, (255, 0, 0), 3)
                radius = i[2]
                cv2.circle(src, center, radius, (0, 0, 255), 3)

        #**********Az ora 'kiteritese'*******************************************************

        polar = cv2.warpPolar(src, (0, 0), center, radius,
                              cv2.WARP_POLAR_LINEAR)
        (h, w) = polar.shape[:2]
        polar_center = (w / 2, h / 2)
        M = cv2.getRotationMatrix2D(polar_center, 180, 1.0)
        polar = cv2.warpAffine(polar, M, (w, h))
        polar = cv2.resize(polar,
                           None,
                           fx=2.0,
                           fy=1.0,
                           interpolation=cv2.INTER_LINEAR)

        #**********A kiteritett kepen elvegzem az inverz binaris kuszobolest******************

        ret, polar = cv2.threshold(polar, 120, 255, cv2.THRESH_BINARY)

        struct = cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1))
コード例 #29
0
    def center_estimation_Combot2020(sar, lon1st, lat1st, hetero_thresh=0.5):
        hetero_mask = sar.heterogeneity_mask.values < 0.5
        xx, yy = np.meshgrid(sar.lon, sar.lat)
        xx -= lon1st
        yy -= lat1st
        dist = np.sqrt(xx**2 + yy**2) * 110  #km
        dist_mask = dist < 50
        co_contrast = np.nanmax(sar.nrcs_co.values[dist_mask]) - np.nanmin(
            sar.nrcs_co.values[dist_mask])
        cross_contrast = np.nanmax(
            sar.nrcs_cross.values[dist_mask]) - np.nanmin(
                sar.nrcs_cross.values[dist_mask])
        co_is_larger_contrast = co_contrast > cross_contrast

        nrcs = sar.nrcs_co if co_is_larger_contrast else nrcs_cross
        nrcs_masked = np.where(dist_mask, nrcs, np.nanmax(nrcs))
        lat2nd_ind, lon2nd_ind = np.where(
            nrcs_masked == np.nanmin(nrcs_masked))
        lon2nd = sar.lon[lon2nd_ind].values.mean()
        lat2nd = sar.lat[lat2nd_ind].values.mean()
        lon2nd_ind = np.where(sar.lon == lon2nd)[0]
        lat2nd_ind = np.where(sar.lat == lat2nd)[0]

        polar_radius = int(100 / (110 * (sar.lat[0] - sar.lat[1])))
        flags = cv2.INTER_LINEAR + cv2.WARP_FILL_OUTLIERS + cv2.WARP_POLAR_LINEAR
        nrcs_norm = cv2.normalize(nrcs.values * hetero_mask,
                                  None,
                                  0,
                                  255,
                                  cv2.NORM_MINMAX,
                                  dtype=cv2.CV_8U)
        nrcs_polar = cv2.warpPolar(nrcs_norm, (polar_radius, int(360 / 0.5)),
                                   (lon2nd_ind, lat2nd_ind), polar_radius,
                                   flags)
        wind_norm = cv2.normalize(sar.wind_speed.values * hetero_mask,
                                  None,
                                  0,
                                  255,
                                  cv2.NORM_MINMAX,
                                  dtype=cv2.CV_8U)
        wind_polar = cv2.warpPolar(wind_norm, (polar_radius, int(360 / 0.5)),
                                   (lon2nd_ind, lat2nd_ind), polar_radius,
                                   flags)

        nrcs_diff = np.diff(nrcs_polar.astype(np.float), axis=1)
        wind_diff = np.diff(wind_polar.astype(np.float), axis=1)
        diff = nrcs_diff + wind_diff
        blurred_diff = ndi.gaussian_filter(diff, sigma=5)

        eye_extents = np.argmax(blurred_diff, axis=1)  # align with 0.5 deg
        dirs_crockwise_from_east = np.arange(0, 360, 0.5)

        eye_ext_xs = eye_extents * np.cos(
            np.deg2rad(dirs_crockwise_from_east)) + lon2nd_ind
        eye_ext_ys = eye_extents * np.sin(
            np.deg2rad(dirs_crockwise_from_east)) + lat2nd_ind

        x = int(eye_ext_xs.mean())
        y = int(eye_ext_ys.mean())
        lon = sar.lon.values[x]
        lat = sar.lat.values[y]
        misc = {
            "lon2nd": lon2nd,
            "lat2nd": lat2nd,
            "eye_xs": eye_ext_xs,
            "eye_ys": eye_ext_ys
        }
        return lon, lat, misc
コード例 #30
0
 def get_cart(img, radius, width, height):
     flags = cv2.INTER_LINEAR + cv2.WARP_FILL_OUTLIERS + cv2.WARP_INVERSE_MAP
     cart = cv2.warpPolar(img, (width, height), (width // 2, height // 2),
                          radius, flags)
     return cart