黎 飞

黎 飞

1656531600

如何在 Angular 应用程序中使用 HttpParams 传递参数

HttpParams 允许您在 Angular 中使用 HttpClient 请求传递参数,这里我将给您举一个非常简单的示例,说明如何在 Angular 应用程序中使用 HttpParams 传递参数。让我们看看以下步骤:

第 1 步:创建新应用

您可以使用以下命令轻松创建 Angular 应用程序:

ng new my-new-app

第 2 步:导入 HttpClientModule

在这一步中,我们需要将 HttpClientModule 导入到 app.module.ts 文件中。所以让我们像下面这样导入它:

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';  import { AppComponent } from './app.component';import { HttpClientModule } from '@angular/common/http';  @NgModule({  declarations: [    AppComponent  ],  imports: [    BrowserModule,    HttpClientModule  ],  providers: [],  bootstrap: [AppComponent]})export class AppModule { }

第 3 步:更新 TS 文件

现在我们必须为 HttpClient 和 HttpHeaders 使用这个编写代码。所以让我们更新代码如下:

src/app/app.component.ts

import { Component } from '@angular/core';import { HttpClient, HttpParams } from '@angular/common/http';  @Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css']})export class AppComponent {  title = 'fullcal';    /*------------------------------------------  --------------------------------------------  Define constructor  --------------------------------------------  --------------------------------------------*/  constructor(private http: HttpClient) {}    /*------------------------------------------  --------------------------------------------  Define ngOnInit()  --------------------------------------------  --------------------------------------------*/  ngOnInit() {      let auth_token = "asasa21212....";      let params = new HttpParams();    params = params.append('_page', 1);    params = params.append('_limit', 10);      const requestOptions = { params: params };          this.http        .get('http://localhost:8001/events.php', requestOptions)        .subscribe((res: any) => {            console.log(res);        });  }}

第 4 步:创建 API

在这里,我们将创建一个简单的 php 文件调用 events.php 并将两个事件作为 json 返回。所以让我们创建文件并运行 php 应用程序。

事件.php

<?php  header("Access-Control-Allow-Origin: *");header("Access-Control-Allow-Methods: PUT, GET, POST");header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");  $parameters = $_GET;echo json_encode($parameters);

现在,您必须使用以下命令运行此文件:

php -S localhost:8001

运行 Angular 应用程序:

所有必需的步骤都已完成,现在您必须输入以下命令并按 Enter 键运行 Angular 应用程序:

ng serve

现在,转到您的网络浏览器,输入给定的 URL 并查看应用程序输出:

http://localhost:4200

我希望它可以帮助你...

资料来源:https ://www.itsolutionstuff.com/post/how-to-use-httpparams-in-angular-13example.html

#http #params #angular 

如何在 Angular 应用程序中使用 HttpParams 传递参数

Passar Parâmetros Usando HttpParams No Aplicativo Angular

HttpParams permite passar parâmetros com requisição HttpClient em angular, Aqui vou dar um exemplo bem simples de como passar parâmetros usando HttpParams em angular app. Vejamos abaixo os passos:

Etapa 1: criar um novo aplicativo

Você pode criar facilmente seu aplicativo angular usando o comando abaixo:

ng new my-new-app

Etapa 2: importar HttpClientModule

Nesta etapa, precisamos importar HttpClientModule para o arquivo app.module.ts. então vamos importá-lo como abaixo:

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Etapa 3: atualizar o arquivo TS

Agora temos que usar este código de gravação para HttpClient e HttpHeaders. Então vamos atualizar o código como abaixo:

src/app/app.component.ts

import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'fullcal';
  
  /*------------------------------------------
  --------------------------------------------
  Define constructor
  --------------------------------------------
  --------------------------------------------*/
  constructor(private http: HttpClient) {}
  
  /*------------------------------------------
  --------------------------------------------
  Define ngOnInit()
  --------------------------------------------
  --------------------------------------------*/
  ngOnInit() {
  
    let auth_token = "asasa21212....";
  
    let params = new HttpParams();
    params = params.append('_page', 1);
    params = params.append('_limit', 10);
  
    const requestOptions = { params: params };
      
    this.http
        .get('http://localhost:8001/events.php', requestOptions)
        .subscribe((res: any) => {
            console.log(res);
        });

  }
}

Etapa 4: criar API

Aqui, vamos criar um arquivo php simples chamado events.php e retornar dois eventos como json. então vamos criar o arquivo e executar o php app.

eventos.php

<?php
  
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
  
$parameters = $_GET;
echo json_encode($parameters);

Agora, você deve executar este arquivo usando o comando abaixo:

php -S localhost:8001

Execute o aplicativo angular:

Todas as etapas necessárias foram feitas, agora você deve digitar o comando abaixo e pressionar enter para executar o aplicativo Angular:

ng serve

Agora, vá para o seu navegador da web, digite o URL fornecido e visualize a saída do aplicativo:

http://localhost:4200

Espero que possa te ajudar...

Fonte: https://www.itsolutionstuff.com/post/how-to-use-httpparams-in-angular-13example.html

#http #params #angular 

 Passar Parâmetros Usando HttpParams No Aplicativo Angular
Hoang  Ha

Hoang Ha

1656529200

Cách Chuyển Các Tham Số Bằng HttpParams Trong Angular App

HttpParams cho phép bạn truyền tham số với yêu cầu HttpClient ở dạng góc, Sau đây tôi sẽ cung cấp cho bạn một ví dụ rất đơn giản về cách truyền tham số bằng HttpParams trong ứng dụng góc. Hãy xem các bước dưới đây:

Bước 1: Tạo ứng dụng mới

Bạn có thể dễ dàng tạo ứng dụng góc cạnh của mình bằng lệnh dưới đây:

ng new my-new-app

Bước 2: Nhập HttpClientModule

Trong bước này, chúng ta cần nhập HttpClientModule vào tệp app.module.ts. vì vậy hãy nhập nó như sau:

src / app / app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Bước 3: Cập nhật tệp TS

Bây giờ chúng ta phải sử dụng mã viết này cho HttpClient và HttpHeaders. Vì vậy, hãy cập nhật mã như dưới đây:

src / app / app.component.ts

import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'fullcal';
  
  /*------------------------------------------
  --------------------------------------------
  Define constructor
  --------------------------------------------
  --------------------------------------------*/
  constructor(private http: HttpClient) {}
  
  /*------------------------------------------
  --------------------------------------------
  Define ngOnInit()
  --------------------------------------------
  --------------------------------------------*/
  ngOnInit() {
  
    let auth_token = "asasa21212....";
  
    let params = new HttpParams();
    params = params.append('_page', 1);
    params = params.append('_limit', 10);
  
    const requestOptions = { params: params };
      
    this.http
        .get('http://localhost:8001/events.php', requestOptions)
        .subscribe((res: any) => {
            console.log(res);
        });

  }
}

Bước 4: Tạo API

Ở đây, chúng ta sẽ tạo tệp php đơn giản gọi sự kiện.php và trả về hai sự kiện dưới dạng json. vì vậy hãy tạo tệp và chạy ứng dụng php.

event.php

<?php
  
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
  
$parameters = $_GET;
echo json_encode($parameters);

Bây giờ, bạn phải chạy tệp này bằng lệnh dưới đây:

php -S localhost:8001

Chạy ứng dụng Angular:

Tất cả các bước cần thiết đã được thực hiện, bây giờ bạn phải nhập lệnh dưới đây và nhấn enter để chạy ứng dụng Angular:

ng serve

Bây giờ, hãy truy cập trình duyệt web của bạn, nhập URL đã cho và xem đầu ra ứng dụng:

http://localhost:4200

Tôi hy vọng nó có thể giúp bạn...

Nguồn: https://www.itsolutionstuff.com/post/how-to-use-httpparams-in-angular-13example.html

#http #params #angular 

Cách Chuyển Các Tham Số Bằng HttpParams Trong Angular App
Léon  Peltier

Léon Peltier

1656528000

Passer Des Paramètres à L'aide De HttpParams Dans L'application Angula

HttpParams vous permet de passer des paramètres avec la requête HttpClient dans angular. Ici, je vais vous donner un exemple très simple de la façon de passer des paramètres à l'aide de HttpParams dans une application angulaire. Voyons ci-dessous les étapes :

Étape 1 : Créer une nouvelle application

Vous pouvez facilement créer votre application angulaire en utilisant la commande ci-dessous :

ng new my-new-app

Étape 2 : Importer HttpClientModule

Dans cette étape, nous devons importer HttpClientModule dans le fichier app.module.ts. alors importons-le comme ci-dessous:

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Étape 3 : Mettre à jour le fichier TS

Nous devons maintenant utiliser ce code d'écriture pour HttpClient et HttpHeaders. Alors mettons à jour le code comme ci-dessous :

src/app/app.component.ts

import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'fullcal';
  
  /*------------------------------------------
  --------------------------------------------
  Define constructor
  --------------------------------------------
  --------------------------------------------*/
  constructor(private http: HttpClient) {}
  
  /*------------------------------------------
  --------------------------------------------
  Define ngOnInit()
  --------------------------------------------
  --------------------------------------------*/
  ngOnInit() {
  
    let auth_token = "asasa21212....";
  
    let params = new HttpParams();
    params = params.append('_page', 1);
    params = params.append('_limit', 10);
  
    const requestOptions = { params: params };
      
    this.http
        .get('http://localhost:8001/events.php', requestOptions)
        .subscribe((res: any) => {
            console.log(res);
        });

  }
}

Étape 4 : Créer une API

Ici, nous allons créer un simple appel de fichier php events.php et renvoyer deux événements au format json. alors créons un fichier et exécutons l'application php.

événements.php

<?php
  
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
  
$parameters = $_GET;
echo json_encode($parameters);

Maintenant, vous devez exécuter ce fichier en utilisant la commande ci-dessous :

php -S localhost:8001

Exécutez l'application angulaire :

Toutes les étapes requises ont été effectuées, vous devez maintenant taper la commande ci-dessous et appuyer sur Entrée pour exécuter l'application Angular :

ng serve

Maintenant, allez dans votre navigateur Web, tapez l'URL donnée et affichez la sortie de l'application :

http://localhost:4200

J'espère que cela peut vous aider...

Source : https://www.itsolutionstuff.com/post/how-to-use-httpparams-in-angular-13example.html

#http #params #angular 

Passer Des Paramètres à L'aide De HttpParams Dans L'application Angula

Pasar Parámetros Usando HttpParams En La Aplicación Angular

HttpParams le permite pasar parámetros con la solicitud HttpClient en angular. Aquí le daré un ejemplo muy simple de cómo pasar parámetros usando HttpParams en la aplicación angular. Veamos a continuación los pasos:

Paso 1: Crear nueva aplicación

Puede crear fácilmente su aplicación angular usando el siguiente comando:

ng new my-new-app

Paso 2: Importar HttpClientModule

En este paso, necesitamos importar HttpClientModule al archivo app.module.ts. así que vamos a importarlo como a continuación:

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Paso 3: Actualice el archivo TS

Ahora tenemos que usar este código de escritura para HttpClient y HttpHeaders. Así que actualicemos el código como se muestra a continuación:

src/app/app.component.ts

import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'fullcal';
  
  /*------------------------------------------
  --------------------------------------------
  Define constructor
  --------------------------------------------
  --------------------------------------------*/
  constructor(private http: HttpClient) {}
  
  /*------------------------------------------
  --------------------------------------------
  Define ngOnInit()
  --------------------------------------------
  --------------------------------------------*/
  ngOnInit() {
  
    let auth_token = "asasa21212....";
  
    let params = new HttpParams();
    params = params.append('_page', 1);
    params = params.append('_limit', 10);
  
    const requestOptions = { params: params };
      
    this.http
        .get('http://localhost:8001/events.php', requestOptions)
        .subscribe((res: any) => {
            console.log(res);
        });

  }
}

Paso 4: Crear API

Aquí, crearemos un archivo php simple llamado events.php y devolveremos dos eventos como json. así que vamos a crear un archivo y ejecutar la aplicación php.

eventos.php

<?php
  
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
  
$parameters = $_GET;
echo json_encode($parameters);

Ahora, debe ejecutar este archivo con el siguiente comando:

php -S localhost:8001

Ejecute la aplicación Angular:

Se han realizado todos los pasos requeridos, ahora debe escribir el siguiente comando y presionar enter para ejecutar la aplicación Angular:

ng serve

Ahora, vaya a su navegador web, escriba la URL dada y vea el resultado de la aplicación:

http://localhost:4200

Espero que te pueda ayudar...

Fuente: https://www.itsolutionstuff.com/post/how-to-use-httpparams-in-angular-13example.html

#http #params #angular 

 Pasar Parámetros Usando HttpParams En La Aplicación Angular
藤本  結衣

藤本 結衣

1656523200

AngularアプリでHttpParamsを使用してパラメーターを渡す方法

HttpParamsを使用すると、AngularでHttpClientリクエストを使用してパラメーターを渡すことができます。ここでは、AngularアプリでHttpParamsを使用してパラメーターを渡す方法の非常に簡単な例を示します。以下の手順を見てみましょう。

ステップ1:新しいアプリを作成する

以下のコマンドを使用して、Angularアプリを簡単に作成できます。

ng new my-new-app

ステップ2:HttpClientModuleをインポートする

このステップでは、HttpClientModuleをapp.module.tsファイルにインポートする必要があります。それでは、次のようにインポートしましょう。

src / app / app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

ステップ3:TSファイルを更新する

次に、この書き込みコードをHttpClientとHttpHeadersに使用する必要があります。それでは、次のようにコードを更新しましょう。

src / app / app.component.ts

import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'fullcal';
  
  /*------------------------------------------
  --------------------------------------------
  Define constructor
  --------------------------------------------
  --------------------------------------------*/
  constructor(private http: HttpClient) {}
  
  /*------------------------------------------
  --------------------------------------------
  Define ngOnInit()
  --------------------------------------------
  --------------------------------------------*/
  ngOnInit() {
  
    let auth_token = "asasa21212....";
  
    let params = new HttpParams();
    params = params.append('_page', 1);
    params = params.append('_limit', 10);
  
    const requestOptions = { params: params };
      
    this.http
        .get('http://localhost:8001/events.php', requestOptions)
        .subscribe((res: any) => {
            console.log(res);
        });

  }
}

ステップ4:APIを作成する

ここでは、events.phpという単純なphpファイルを作成し、2つのイベントをjsonとして返します。それでは、ファイルを作成してphpアプリを実行しましょう。

events.php

<?php
  
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
  
$parameters = $_GET;
echo json_encode($parameters);

ここで、次のコマンドを使用してこのファイルを実行する必要があります。

php -S localhost:8001

Angularアプリを実行します:

必要な手順はすべて完了しました。次に、以下のコマンドを入力し、Enterキーを押してAngularアプリを実行する必要があります。

ng serve

次に、Webブラウザーに移動し、指定されたURLを入力して、アプリの出力を表示します。

http://localhost:4200

お役に立てば幸いです...

ソース:https ://www.itsolutionstuff.com/post/how-to-use-httpparams-in-angular-13example.html

#http #params #angular 

AngularアプリでHttpParamsを使用してパラメーターを渡す方法

How to Pass Parameters using HttpParams in Angular App

HttpParams allows you to pass parameters with HttpClient request in angular, Here I will give you a very simple example of how to pass parameters using HttpParams in angular app. Let's see below steps:

Step 1: Create New App

You can easily create your angular app using the below command:

ng new my-new-app

Step 2: Import HttpClientModule

In this step, we need to import HttpClientModule to app.module.ts file. so let's import it as like bellow:

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
  
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Step 3: Update TS File

Now we have to use this write code for HttpClient and HttpHeaders. So let's updated code as like bellow:

src/app/app.component.ts

import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'fullcal';
  
  /*------------------------------------------
  --------------------------------------------
  Define constructor
  --------------------------------------------
  --------------------------------------------*/
  constructor(private http: HttpClient) {}
  
  /*------------------------------------------
  --------------------------------------------
  Define ngOnInit()
  --------------------------------------------
  --------------------------------------------*/
  ngOnInit() {
  
    let auth_token = "asasa21212....";
  
    let params = new HttpParams();
    params = params.append('_page', 1);
    params = params.append('_limit', 10);
  
    const requestOptions = { params: params };
      
    this.http
        .get('http://localhost:8001/events.php', requestOptions)
        .subscribe((res: any) => {
            console.log(res);
        });

  }
}

Step 4: Create API

Here, we will create simple php file call events.php and return two events as json. so let's create file and run php app.

events.php

<?php
  
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
  
$parameters = $_GET;
echo json_encode($parameters);

Now, you have to run this file using bellow command:

php -S localhost:8001

Run Angular App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Angular app:

ng serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:4200

I hope it can help you...

Source: https://www.itsolutionstuff.com/post/how-to-use-httpparams-in-angular-13example.html

#http #params #angular 

How to Pass Parameters using HttpParams in Angular App
Michio JP

Michio JP

1629796171

Focal Transformer | Official Implementation of Focal Transformer

Focal Transformer

This is the official implementation of our Focal Transformer -- "Focal Self-attention for Local-Global Interactions in Vision Transformers", by Jianwei Yang, Chunyuan Li, Pengchuan Zhang, Xiyang Dai, Bin Xiao, Lu Yuan and Jianfeng Gao.

Introduction

Our Focal Transfomer introduced a new self-attention mechanism called focal self-attention for vision transformers. In this new mechanism, each token attends the closest surrounding tokens at fine granularity but the tokens far away at coarse granularity, and thus can capture both short- and long-range visual dependencies efficiently and effectively.

With our Focal Transformers, we achieved superior performance over the state-of-the-art vision Transformers on a range of public benchmarks. In particular, our Focal Transformer models with a moderate size of 51.1M and a larger size of 89.8M achieve 83.6 and 84.0 Top-1 accuracy, respectively, on ImageNet classification at 224x224 resolution. Using Focal Transformers as the backbones, we obtain consistent and substantial improvements over the current state-of-the-art methods for 6 different object detection methods trained with standard 1x and 3x schedules. Our largest Focal Transformer yields 58.7/58.9 box mAPs and 50.9/51.3 mask mAPs on COCO mini-val/test-dev, and 55.4 mIoU on ADE20K for semantic segmentation.

Benchmarking

Image Classification on ImageNet-1K

ModelPretrainUse ConvResolutionacc@1acc@5#paramsFLOPsCheckpointConfig
Focal-TIN-1KNo22482.295.928.9M4.9Gdownloadyaml
Focal-TIN-1KYes22482.796.130.8M4.9Gdownloadyaml
Focal-SIN-1KNo22483.696.251.1M9.4Gdownloadyaml
Focal-BIN-1KNo22484.096.589.8M16.4Gdownloadyaml

Object Detection and Instance Segmentation on COCO

Mask R-CNN

BackbonePretrainLr Schd#paramsFLOPsbox mAPmask mAP
Focal-TImageNet-1K1x49M291G44.841.0
Focal-TImageNet-1K3x49M291G47.242.7
Focal-SImageNet-1K1x71M401G47.442.8
Focal-SImageNet-1K3x71M401G48.843.8
Focal-BImageNet-1K1x110M533G47.843.2
Focal-BImageNet-1K3x110M533G49.043.7

RetinaNet

BackbonePretrainLr Schd#paramsFLOPsbox mAP
Focal-TImageNet-1K1x39M265G43.7
Focal-TImageNet-1K3x39M265G45.5
Focal-SImageNet-1K1x62M367G45.6
Focal-SImageNet-1K3x62M367G47.3
Focal-BImageNet-1K1x101M514G46.3
Focal-BImageNet-1K3x101M514G46.9

Other detection methods

BackbonePretrainMethodLr Schd#paramsFLOPsbox mAP
Focal-TImageNet-1KCascade Mask R-CNN3x87M770G51.5
Focal-TImageNet-1KATSS3x37M239G49.5
Focal-TImageNet-1KRepPointsV23x45M491G51.2
Focal-TImageNet-1KSparse R-CNN3x111M196G49.0

Semantic Segmentation on ADE20K

BackbonePretrainMethodResolutionIters#paramsFLOPsmIoUmIoU (MS)
Focal-TImageNet-1KUPerNet512x512160k62M998G45.847.0
Focal-SImageNet-1KUPerNet512x512160k85M1130G48.050.0
Focal-BImageNet-1KUPerNet512x512160k126M1354G49.050.5
Focal-LImageNet-22KUPerNet640x640160k240M3376G54.055.4

Getting Started

Citation

If you find this repo useful to your project, please consider to cite it with following bib:

@misc{yang2021focal,
    title={Focal Self-attention for Local-Global Interactions in Vision Transformers}, 
    author={Jianwei Yang and Chunyuan Li and Pengchuan Zhang and Xiyang Dai and Bin Xiao and Lu Yuan and Jianfeng Gao},
    year={2021},
    eprint={2107.00641},
    archivePrefix={arXiv},
    primaryClass={cs.CV}
}

Acknowledgement

Our codebase is built based on Swin-Transformer. We thank the authors for the nicely organized code!

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

Download Details:

Author: microsoft

Source Code: https://github.com/microsoft/Focal-Transformer 

Michio JP

Michio JP

1629795102

Demystifying Local Vision Transformer with PyTorch

This is the official PyTorch implementation of our paper. We simply replace local self attention by (dynamic) depth-wise convolution with lower computational cost. The performance is on par with the Swin Transformer.

Besides, the main contribution of our paper is the theorical and detailed comparison between depth-wise convolution and local self attention from three aspects: sparse connectivity, weight sharing and dynamic weight. By this paper, we want community to rethinking the local self attention and depth-wise convolution, and the basic model architeture designing rules.

Codes and models for object detection and semantic segmentation are avaliable in Detection and Segmentation.

We also give MLP based Swin Transformer models and Inhomogenous dynamic convolution in the ablation studies. These codes and models will coming soon.

Reference

@article{han2021demystifying,
  title={Demystifying Local Vision Transformer: Sparse Connectivity, Weight Sharing, and Dynamic Weight},
  author={Han, Qi and Fan, Zejia and Dai, Qi and Sun, Lei and Cheng, Ming-Ming and Liu, Jiaying and Wang, Jingdong},
  journal={arXiv preprint arXiv:2106.04263},
  year={2021}
}

1. Requirements

torch>=1.5.0, torchvision, timm, pyyaml; apex-amp

data perpare: ImageNet dataset with the following structure:

│imagenet/
├──train/
│  ├── n01440764
│  │   ├── n01440764_10026.JPEG
│  │   ├── n01440764_10027.JPEG
│  │   ├── ......
│  ├── ......
├──val/
│  ├── n01440764
│  │   ├── ILSVRC2012_val_00000293.JPEG
│  │   ├── ILSVRC2012_val_00002138.JPEG
│  │   ├── ......
│  ├── ......

2. Trainning

For tiny model, we train with batch-size 128 on 8 GPUs. When trainning base model, we use batch-size 64 on 16 GPUs with OpenMPI to keep the total batch-size unchanged. (With the same trainning setting, the base model couldn't train with AMP due to the anomalous gradient values.)

Please change the data path in sh scripts first.

For tiny model:

bash scripts/run_dwnet_tiny_patch4_window7_224.sh bash scripts/run_dynamic_dwnet_tiny_patch4_window7_224.sh

For base model, use multi node with OpenMPI:

bash scripts/run_dwnet_base_patch4_window7_224.sh bash scripts/run_dynamic_dwnet_base_patch4_window7_224.sh

3. Evaluation

python -m torch.distributed.launch --nproc_per_node 1 --master_port 12345 main.py --cfg configs/change_to_config_file --resume /path/to/model --data-path /path/to/imagenet --eval

4. Models

Models are provided by training on ImageNet with resolution 224.

Model#paramsFLOPsTop1 AccDownload
dwnet_tiny24M3.8G81.2github
dynamic_dwnet_tiny51M3.8G81.8github
dwnet_base74M12.9G83.2github
dynamic_dwnet_base162M13.0G83.2github

Detection (see Detection for details):

BackbonePretrainLr Schdbox mAPmask mAP#paramsFLOPsconfigmodel
DWNet-TImageNet-1K3x49.943.482M730Gconfiggithub
DWNet-BImageNet-1K3x51.044.1132M924Gconfiggithub
Dynamic-DWNet-TImageNet-1K3x50.543.7108M730Gconfiggithub
Dynamic-DWNet-BImageNet-1K3x51.244.4219M924Gconfiggithub

Segmentation (see Segmentation for details):

BackbonePretrainLr SchdmIoU#paramsFLOPsconfigmodel
DWNet-TImageNet-1K160K45.556M928Gconfiggithub
DWNet-BImageNet-1K160K48.3108M1129Gconfiggithub
Dynamic-DWNet-TImageNet-1K160K45.783M928Gconfiggithub
Dynamic-DWNet-BImageNet-1K160K48.0195M1129Gconfiggithub

LICENSE

This repo is under the MIT license. Some codes are borrow from Swin Transformer.

Download Details:

Author: Atten4Vis

Source Code: https://github.com/Atten4Vis/DemystifyLocalViT 

Michio JP

Michio JP

1629564829

HRFormer | High-Resolution Transformer for Dense Prediction

High-Resolution Transformer for Dense Prediction

This is the official implementation of High-Resolution Transformer (HRT). We present a High-Resolution Transformer (HRT) that learns high-resolution representations for dense prediction tasks, in contrast to the original Vision Transformer that produces low-resolution representations and has high memory and computational cost. We take advantage of the multi-resolution parallel design introduced in high-resolution convolutional networks (HRNet), along with local-window self-attention that performs self-attention over small non-overlapping image windows, for improving the memory and computation efficiency. In addition, we introduce a convolution into the FFN to exchange information across the disconnected image windows. We demonstrate the effectiveness of the High-Resolution Transformeron human pose estimation and semantic segmentation tasks.

  • The High-Resolution Transformer architecture:

An official implementation of the High-Resolution Transformer for Dense Prediction

Pose estimation

2d Human Pose Estimation

Results on COCO val2017 with detector having human AP of 56.4 on COCO val2017 dataset

BackboneInput SizeAPAP50AP75ARMARLARckptlogscript
HRT-S256x19274.0%90.2%81.2%70.4%80.7%79.4%ckptlogscript
HRT-S384x28875.6%90.3%82.2%71.6%82.5%80.7%ckptlogscript
HRT-B256x19275.6%90.8%82.8%71.7%82.6%80.8%ckptlogscript
HRT-B384x28877.2%91.0%83.6%73.2%84.2%82.0%ckptlogscript

Results on COCO test-dev with detector having human AP of 56.4 on COCO val2017 dataset

BackboneInput SizeAPAP50AP75ARMARLARckptlogscript
HRT-S384x28874.5%92.3%82.1%70.7%80.6%79.8%ckptlogscript
HRT-B384x28876.2%92.7%83.8%72.5%82.3%81.2%ckptlogscript

The models are first pre-trained on ImageNet-1K dataset, and then fine-tuned on COCO val2017 dataset.

Semantic segmentation

Cityscapes

Performance on the Cityscapes dataset. The models are trained and tested with input size of 512x1024 and 1024x2048 respectively.

MethodsBackboneWindow SizeTrain SetTest SetIterationsBatch SizeOHEMmIoUmIoU (Multi-Scale)Logckptscript
OCRNetHRT-S7x7TrainVal800008Yes80.081.0logckptscript
OCRNetHRT-B7x7TrainVal800008Yes81.482.0logckptscript
OCRNetHRT-B15x15TrainVal800008Yes81.982.6logckptscript

PASCAL-Context

The models are trained with the input size of 520x520, and tested with original size.

MethodsBackboneWindow SizeTrain SetTest SetIterationsBatch SizeOHEMmIoUmIoU (Multi-Scale)Logckptscript
OCRNetHRT-S7x7TrainVal6000016Yes53.854.6logckptscript
OCRNetHRT-B7x7TrainVal6000016Yes56.357.1logckptscript
OCRNetHRT-B15x15TrainVal6000016Yes57.658.5logckptscript

COCO-Stuff

The models are trained with input size of 520x520, and tested with original size.

MethodsBackboneWindow SizeTrain SetTest SetIterationsBatch SizeOHEMmIoUmIoU (Multi-Scale)Logckptscript
OCRNetHRT-S7x7TrainVal6000016Yes37.938.9logckptscript
OCRNetHRT-B7x7TrainVal6000016Yes41.642.5logckptscript
OCRNetHRT-B15x15TrainVal6000016Yes42.443.3logckptscript

ADE20K

The models are trained with input size of 520x520, and tested with original size. The results with window size 15x15 will be updated latter.

MethodsBackboneWindow SizeTrain SetTest SetIterationsBatch SizeOHEMmIoUmIoU (Multi-Scale)Logckptscript
OCRNetHRT-S7x7TrainVal1500008Yes44.045.1logckptscript
OCRNetHRT-B7x7TrainVal1500008Yes46.347.6logckptscript
OCRNetHRT-B13x13TrainVal1500008Yes48.750.0logckptscript
OCRNetHRT-B15x15TrainVal1500008Yes-----

Classification

Results on ImageNet-1K

Backboneacc@1acc@5#paramsFLOPsckptlogscript
HRT-T78.6%94.2%8.0M1.83Gckptlogscript
HRT-S81.2%95.6%13.5M3.56Gckptlogscript
HRT-B82.8%96.3%50.3M13.71Gckptlogscript

Citation

If you find this project useful in your research, please consider cite:

@article{YuanFHZCW21,
  title={HRT: High-Resolution Transformer for Dense Prediction},
  author={Yuhui Yuan and Rao Fu and Lang Huang and Chao Zhang and Xilin Chen and Jingdong Wang},
  booktitle={arXiv},
  year={2021}
}

Acknowledgment

This project is developed based on the Swin-Transformer, openseg.pytorch, and mmpose.

git diff-index HEAD
git subtree add -P pose  

Download Details:

Author: HRNet

Source Code: https://github.com/HRNet/HRFormer