python类rot90()的实例源码

pi_camera.py 文件源码 项目:Robo-Plot 作者: JackBuck 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def take_photo_at(self, camera_centre):
        with picamera.PiCamera() as camera:
            camera.resolution = config.CAMERA_RESOLUTION
            camera.framerate = 24
            with picamera.array.PiRGBArray(camera) as output:
                camera.capture(output, 'bgr', use_video_port=True)
                outputarray = output.array

            # Rotate image to oriented it with paper.
            outputarray = np.rot90(outputarray, 3)

            # Save photo.
            filename = datetime.datetime.now().strftime("%M%S.%f_") + \
                       str(camera_centre[0]) \
                       + '_' \
                       + str(camera_centre[1]) + '_Photo_' + str(self._photo_index) + '.jpg'

            cv2.imwrite(os.path.join(config.debug_output_folder, filename), outputarray)
            self._photo_index += 1

            return outputarray
DRIP.py 文件源码 项目:DRIP-SLIP 作者: NASA-DEVELOP 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def sum48(newFile,extent):
    currentSum=loadtxt(os.path.join(getCurrentDirectory(),'Sum48','sum48.txt'),dtype='float',delimiter=',')
    historicFiles=sorted(glob.glob(os.path.join(getCurrentDirectory(),'Sum48','Files','*txt')))
    lastFile=loadtxt(os.path.join(getCurrentDirectory(),'Sum48','Files',historicFiles[0]),dtype='float',delimiter=',')
    currentSum=currentSum-lastFile
    currentSum=currentSum+newFile
    np.savetxt(os.path.join(getCurrentDirectory(),'Sum48','sum48.txt'),currentSum,delimiter=',')
    rotatedSum = np.rot90(currentSum)
    tiffFiles=glob.glob(os.path.join(getCurrentDirectory(),'Sum48','Tiffs','*.TIF'))
    if not tiffFiles:
        lastTifNum='1'
    else:
        tiffFiles=natsorted(tiffFiles,alg=ns.IC)
        lastTif=tiffFiles[-1]
        lastTifNum=str(int(lastTif[lastTif.rfind('_')+1:lastTif.rfind('.')])+1)
    array2raster(os.path.join(getCurrentDirectory(),'Sum48','Tiffs',timeStr[-11:-7]) + '_48HourSum_' + lastTifNum + '.TIF',[extent[0],extent[3]],extent[4],extent[5],rotatedSum,gdalconst.GDT_Float32)
    while len(tiffFiles)>48:
        os.remove(tiffFiles[0])
        tiffFiles=natsorted(glob.glob(os.path.join(getCurrentDirectory(),'Sum48','Tiffs','*.TIF')),alg=ns.IC)
    os.remove(historicFiles[0])

#sums the past 72 hours of rainfall, sends an email if exceeds threshold
DRIP.py 文件源码 项目:DRIP-SLIP 作者: NASA-DEVELOP 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def sum72(newFile,extent):
    currentSum=loadtxt(os.path.join(getCurrentDirectory(),'Sum72','sum72.txt'),dtype='float',delimiter=',')
    historicFiles=sorted(glob.glob(os.path.join(getCurrentDirectory(),'Sum72','Files','*txt')))
    lastFile=loadtxt(os.path.join(getCurrentDirectory(),'Sum72','Files',historicFiles[0]),dtype='float',delimiter=',')
    currentSum=currentSum-lastFile
    currentSum=currentSum+newFile
    np.savetxt(os.path.join(getCurrentDirectory(),'Sum72','sum72.txt'),currentSum,delimiter=',')
    rotatedSum = np.rot90(currentSum)
    tiffFiles=glob.glob(os.path.join(getCurrentDirectory(),'Sum72','Tiffs','*.TIF'))
    if not tiffFiles:
        lastTifNum='1'
    else:
        tiffFiles=natsorted(tiffFiles,alg=ns.IC)
        lastTif=tiffFiles[-1]
        lastTifNum=str(int(lastTif[lastTif.rfind('_')+1:lastTif.rfind('.')])+1)
    array2raster(os.path.join(getCurrentDirectory(),'Sum72','Tiffs',timeStr[-11:-7]) + '_72HourSum_' + lastTifNum + '.TIF',[extent[0],extent[3]],extent[4],extent[5],rotatedSum,gdalconst.GDT_Float32)
    while len(tiffFiles)>48:
        os.remove(tiffFiles[0])
        tiffFiles=natsorted(glob.glob(os.path.join(getCurrentDirectory(),'Sum72','Tiffs','*.TIF')),alg=ns.IC)
    os.remove(historicFiles[0])

#sends an e-mail containing "attachment", currently to the authors
go.py 文件源码 项目:RocAlphaGo 作者: Rochester-NRT 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def symmetries(self):
        """returns a list of 8 GameState objects:
        all reflections and rotations of the current board

        does not check for duplicates
        """
        copies = [self.copy() for i in range(8)]
        # copies[0] is the original.
        # rotate CCW 90
        copies[1].board = np.rot90(self.board,1)
        # rotate 180
        copies[2].board = np.rot90(self.board,2)
        # rotate CCW 270
        copies[3].board = np.rot90(self.board,3)
        # mirror left-right
        copies[4].board = np.fliplr(self.board)
        # mirror up-down
        copies[5].board = np.flipud(self.board)
        # mirror \ diagonal
        copies[6].board = np.transpose(self.board)
        # mirror / diagonal (equivalently: rotate 90 CCW then flip LR)
        copies[7].board = np.fliplr(copies[1].board)
        return copies
MirrorEngine.py 文件源码 项目:go-NN 作者: TheDuck314 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def pick_move(self, color):
        if not self.opponent_passed and self.last_opponent_play:
            mirror_x = self.board.N - self.last_opponent_play[0] - 1
            mirror_y = self.board.N - self.last_opponent_play[1] - 1
            if self.board.play_is_legal(mirror_x, mirror_y, color):
                return (mirror_x, mirror_y)

        enemy_stones = (self.board.vertices == flipped_color[color])
        our_stones = (self.board.vertices == color)
        rot_enemy_stones = np.rot90(enemy_stones, 2)

        play_vertices = np.logical_and(rot_enemy_stones, np.logical_not(our_stones))
        play_vertices =  np.logical_and(play_vertices, np.logical_not(enemy_stones))

        for x in xrange(self.board.N):
            for y in xrange(self.board.N):
                if play_vertices[x,y] and self.board.play_is_legal(x, y, color):
                    return (x,y)

        center = (self.board.N/2, self.board.N/2)
        if self.board[center] == Color.Empty and self.board.play_is_legal(center[0], center[1], color):
            return center

        return None
sudoku_steps.py 文件源码 项目:pyku 作者: dubvulture 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def extract_digits(self, image):
        """
        Extract digits from a binary image representing a sudoku
        :param image: binary image/sudoku
        :return: array of digits and their probabilities
        """
        prob = np.zeros(4, dtype=np.float32)
        digits = np.zeros((4, 9, 9), dtype=object)
        for i in range(4):
            labeled, features = label(image, structure=CROSS)
            objs = find_objects(labeled)
            for obj in objs:
                roi = image[obj]
                # center of bounding box
                cy = (obj[0].stop + obj[0].start) / 2
                cx = (obj[1].stop + obj[1].start) / 2
                dists = cdist([[cy, cx]], CENTROIDS, 'euclidean')
                pos = np.argmin(dists)
                cy, cx = pos % 9, pos / 9
                # 28x28 image, center relative to sudoku
                prediction = self.classifier.classify(morph(roi))
                if digits[i, cy, cx] is 0:
                    # Newly found digit
                    digits[i, cy, cx] = prediction
                    prob[i] += prediction[0, 0]
                elif prediction[0, 0] > digits[i, cy, cx][0, 0]:
                    # Overlapping! (noise), choose the most probable prediction
                    prob[i] -= digits[i, cy, cx][0, 0]
                    digits[i, cy, cx] = prediction
                    prob[i] += prediction[0, 0]
            image = np.rot90(image)
        logging.info(prob)
        return digits[np.argmax(prob)]
sudoku.py 文件源码 项目:pyku 作者: dubvulture 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def extract_digits(self, image):
        """
        Extract digits from a binary image representing a sudoku
        :param image: binary image/sudoku
        :return: array of digits and their probabilities
        """
        prob = np.zeros(4, dtype=np.float32)
        digits = np.zeros((4, 9, 9), dtype=object)
        for i in range(4):
            labeled, features = label(image, structure=CROSS)
            objs = find_objects(labeled)
            for obj in objs:
                roi = image[obj]
                # center of bounding box
                cy = (obj[0].stop + obj[0].start) / 2
                cx = (obj[1].stop + obj[1].start) / 2
                dists = cdist([[cy, cx]], CENTROIDS, 'euclidean')
                pos = np.argmin(dists)
                cy, cx = pos % 9, pos / 9
                # 28x28 image, center relative to sudoku
                prediction = self.classifier.classify(morph(roi))
                if digits[i, cy, cx] is 0:
                    # Newly found digit
                    digits[i, cy, cx] = prediction
                    prob[i] += prediction[0, 0]
                elif prediction[0, 0] > digits[i, cy, cx][0, 0]:
                    # Overlapping! (noise), choose the most probable prediction
                    prob[i] -= digits[i, cy, cx][0, 0]
                    digits[i, cy, cx] = prediction
                    prob[i] += prediction[0, 0]
            image = np.rot90(image)
        logging.info(prob)
        return digits[np.argmax(prob)]
cnn_visualization.py 文件源码 项目:NumpyDL 作者: oujago 项目源码 文件源码 阅读 50 收藏 0 点赞 0 评论 0
def saveImage(inputImage, name):
    # red = inputImage[:1024]
    # green = inputImage[1024:2048]
    # blue = inputImage[2048:]
    # formatted = np.zeros([3,32,32])
    # formatted[0] = np.reshape(red,[32,32])
    # formatted[1] = np.reshape(green,[32,32])
    # formatted[2] = np.reshape(blue,[32,32])
    # final = np.swapaxes(formatted,0,2)/255
    final = inputImage
    final = np.rot90(np.rot90(np.rot90(final)))
    imsave(name, final)
utils.py 文件源码 项目:marblecutter 作者: mojodna 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def apply_latitude_adjustments(pixels):
    data, (bounds, crs), _ = pixels
    (_, height, width) = data.shape

    ys = np.interp(np.arange(height), [0, height - 1], [bounds[3], bounds[1]])
    xs = np.empty_like(ys)
    xs.fill(bounds[0])

    longitudes, latitudes = warp.transform(crs, WGS84_CRS, xs, ys)

    factors = 1 / np.cos(np.radians(latitudes))

    # convert to 2d array, rotate 270º, scale data
    return PixelCollection(data * np.rot90(np.atleast_2d(factors), 3),
                           pixels.bounds)
watermark_invisiable.py 文件源码 项目:watermark 作者: lishuaijuly 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def extract(self,ori_wmimage,wm, key=None):
        '''
            ??LSB??
        '''
        #???rgb?????????
        if len(ori_wmimage.shape)==3:
            wmimage = ori_wmimage[:,:,0]
        else:
            wmimage = ori_wmimage

        #???????        
        signature = self._gene_signature(wm,key).reshape((16,16))  

        #???????
        ext_sigs = self.ext_sig(wmimage,size=16)
        #ext_sigs.extend(self.ext_sig(np.rot90(wmimage,1)))
        #ext_sigs.extend(self.ext_sig(np.rot90(wmimage,2)))
        #ext_sigs.extend(self.ext_sig(np.rot90(wmimage,3)))

          #?????
        similarity = 0 
        for sig in ext_sigs:
            print(sig)
            print(signature)
            one_similarity = list(np.array(sig.flatten()) - signature.flatten()).count(0) / len(signature.flatten())
            #logging.info('????? : {}'.format(one_similarity))
            similarity = max(similarity,one_similarity )
            break

        logging.debug('???????????????%f (1???0?????????0.7)'  % (similarity))

        return similarity
blind_watermark.py 文件源码 项目:watermark 作者: lishuaijuly 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def inner_extract(self,B,signature):
        sig_size=np.int(np.sqrt(len(signature)))
        size = self.size

        ext_sigs =[] 
        #???????????????
        #???????????????????????
        #  (0,0)    (0,w-32)
        #  (h-32,0)    (h-32,w-32)
        w ,h = B.shape
        embed_pos =[(0,0)]
        embed_pos.append((w-sig_size*size,0))
        embed_pos.append((0,h-sig_size*size))
        embed_pos.append((w-sig_size*size,h-sig_size*size))

        for x,y in embed_pos:
            ext_sig = np.zeros(len(signature),dtype=np.int)

            for i in range(x,x+sig_size*size,size):
                for j in range(y,y+sig_size * size,size):
                    v = cv2.dct(np.float32(B[i:i+size,j:j+size]))
                    if v[size-1,size-1] > self.Q/2:
                        ext_sig[((i-x)//size)*sig_size+(j-y)//size] = 1 


            ext_sigs.append(ext_sig)
            ext_sig_arr = np.array(ext_sig).reshape((sig_size,sig_size))
            ext_sigs.append(np.rot90(ext_sig_arr,1).flatten())
            ext_sigs.append(np.rot90(ext_sig_arr,2).flatten())
            ext_sigs.append(np.rot90(ext_sig_arr,3).flatten())

        return ext_sigs
utils.py 文件源码 项目:train-DeepLab 作者: martinkersner 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def convert_segmentation_mat2numpy(mat_file):
  np_segm = load_mat(mat_file)
  return np.rot90(np.fliplr(np.argmax(np_segm, axis=2)))
utils.py 文件源码 项目:train-DeepLab 作者: martinkersner 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
def load_binary_segmentation(bin_file, dtype='int16'):
  with open(bin_file, 'rb') as bf:
    rows = struct.unpack('i', bf.read(4))[0]
    cols = struct.unpack('i', bf.read(4))[0]
    channels = struct.unpack('i', bf.read(4))[0]

    num_values = rows * cols # expect only one channel in segmentation output
    out = np.zeros(num_values, dtype=np.uint8) # expect only values between 0 and 255

    for i in range(num_values):
      out[i] = np.uint8(struct.unpack('h', bf.read(2))[0])

    return np.rot90(np.fliplr(out.reshape((cols, rows))))
weight_converter.py 文件源码 项目:PSPNet-Keras-tensorflow 作者: Vladkryvoruchko 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def rot90(W):
    for i in range(W.shape[0]):
        for j in range(W.shape[1]):
            W[i, j] = np.rot90(W[i, j], 2)
    return W
b3_data_iter.py 文件源码 项目:kaggle-dstl-satellite-imagery-feature-detection 作者: u1234x1234 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def rot90_mat(mat, k):
    n_mat = np.zeros(mat.shape, dtype=np.float32)
    for i in range(mat.shape[2]):
        n_mat[:, :, i] = np.rot90(mat[:, :, i], k)
    return n_mat
transforms.py 文件源码 项目:KagglePlanetPytorch 作者: Mctigger 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def rotate_90(k=1):
    def call(x):
        x = np.rot90(x, k).copy()
        return x

    return call
lda_visualizer.py 文件源码 项目:quoll 作者: LanguageMachines 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def visualize_document_topics_heatmap(self, outfile, set_topics=False):
        self.sort_doctopics_groups()
        doctopics_raw_hm = numpy.rot90(self.document_topics_raw)
        rows, columns = doctopics_raw_hm.shape
        rownames = self.topic_labels
        columnnames = self.document_names
        pyplot.pcolor(doctopics_raw_hm, norm=None, cmap='Blues')
        pyplot.gca().invert_yaxis()
        if self.group_names:
            ticks_groups = []
            bounds = []
            current_group = False
            start = 0
            for i,doc in enumerate(self.document_names):
                group = self.document_group_dict[doc]
                if group != current_group:
                    if i != 0:
                        bounds.append(i-1)
                        ticks_groups[start+int((i-start)/2)] = current_group
                    current_group = group
                    start=i
                ticks_groups.append('')
            ticks_groups[start+int((i-start)/2)] = current_group
            pyplot.xticks(numpy.arange(columns)+0.5,ticks_groups, fontsize=11)
            if set_topics:
                for index in set_topics:
                    pyplot.axhline(y=index)
                topic_names = self.return_topic_names(set_topics)
                pyplot.yticks(set_topics,topic_names,fontsize=8)
            else:
                pyplot.yticks(numpy.arange(rows)+0.5, rownames, fontsize=8)
            for bound in bounds:
                pyplot.axvline(x=bound)
        pyplot.colorbar(cmap='Blues')
        pyplot.savefig(outfile)
        pyplot.clf()
freeimage.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _rotate(self, im, meta):
            """ Use Orientation information from EXIF meta data to 
            orient the image correctly. Freeimage is also supposed to
            support that, and I am pretty sure it once did, but now it
            does not, so let's just do it in Python.
            Edit: and now it works again, just leave in place as a fallback.
            """
            if self.request.kwargs.get('exifrotate', None) == 2:
                try:
                    ori = meta['EXIF_MAIN']['Orientation']
                except KeyError:  # pragma: no cover
                    pass  # Orientation not available
                else:  # pragma: no cover - we cannot touch all cases
                    # www.impulseadventure.com/photo/exif-orientation.html
                    if ori in [1, 2]:
                        pass
                    if ori in [3, 4]:
                        im = np.rot90(im, 2)
                    if ori in [5, 6]:
                        im = np.rot90(im, 3)
                    if ori in [7, 8]:
                        im = np.rot90(im)
                    if ori in [2, 4, 5, 7]:  # Flipped cases (rare)
                        im = np.fliplr(im)
            return im

    # --
image.py 文件源码 项目:inferno 作者: inferno-pytorch 项目源码 文件源码 阅读 50 收藏 0 点赞 0 评论 0
def image_function(self, image):
        return np.rot90(image, k=self.get_random_variable('k'))
orientation_filter.py 文件源码 项目:image_analysis 作者: CoDaS-Lab 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def noise_amp(self, size):
        """
        DESCRIPTION:
            Creates a size x size matrix of randomly generated noise with
            amplitude values with 1/f slope

        ARGS:
            :size: size of matrix

        RETURNS:
            :returns the amplitudes with noise added
        """

        slope = 1
        x = y = np.linspace(1, size, size)
        xgrid, ygrid = np.meshgrid(x, y)  # coordinates for a square grid
        xgrid = np.subtract(xgrid, size // 2)
        ygrid = np.subtract(ygrid, size // 2)

        amp = self.fft.fftshift(np.divide(np.sqrt(np.square(xgrid) +
                                          np.square(ygrid)),
                                          size * np.sqrt(2)))
        amp = np.rot90(amp, 2)
        amp[0, 0] = 1
        amp = 1 / amp**slope
        amp[0, 0] = 0
        return amp


问题


面经


文章

微信
公众号

扫码关注公众号