다음 항목들을 설치해야 합니다 Windows용 curl 이제 GPU TRT 컨테이너가 Docker에서 실행 중입니다. 다른 Ubuntu 터미널을 열어 Docker 컨테이너로 추론 데이터를 보낼 준비를 합니다. 다음을 사용하세요: Windows용 GNU의 base64 도구. 이를 가장 쉽게 설치하는 방법은 git for Windows 설치 프로그램을 사용하는 것입니다 이 설치 프로그램은 또한 curl 이제 GPU TRT 컨테이너가 Docker에서 실행 중입니다. 다른 Ubuntu 터미널을 열어 Docker 컨테이너로 추론 데이터를 보낼 준비를 합니다. 다음을 사용하세요: base64 설치 중에 "Use Git and optional Unix tools from the Command Prompt"를 선택하면 명령줄 도구들이 포함됩니다.
그런 다음 위와 동일한 명령을 사용할 수 있습니다.
Node.js
우리는 axios 를 이 예제에서 POST 요청을 수행하기 위해 사용하므로 먼저 npm install axios 로 의존성을 설치하세요.
매개변수에 대해 입력 이미지를 선택하세요. 예측에는 모델 결과를 선택하세요. 선택적 구성 속성을 사용하여 경계 상자의 색상과 크기를 변경할 수 있습니다.
string
추가할 이미지의 URL. 이미지가 다른 곳에 호스팅된 경우 사용합니다. (요청 본문에 base64로 인코딩된 이미지를 POST하지 않을 때 필요합니다.)
참고: URL 인코딩하는 것을 잊지 마세요.
classes
string
예측을 특정 클래스에만 제한합니다. 쉼표로 구분된 문자열로 제공하세요.
예시: dog,cat
기본값: 없음 (모든 클래스 표시)
overlap
number
동일 클래스의 바운딩 박스 예측이 단일 박스로 결합되기 전에 허용되는 최대 중첩 비율(0-100 척도).
기본값: 30
confidence
number
0-100 척도의 반환된 예측에 대한 임계값입니다. 낮은 값은 더 많은 예측을 반환하고, 높은 값은 적은 수의 높은 확신 예측을 반환합니다.
기본값: 40
stroke
number
예측 주위에 표시되는 바운딩 박스의 너비(픽셀 단위). ( format 가 매개변수에 대해 입력 이미지를 선택하세요. 예측에는 모델 결과를 선택하세요. 선택적 구성 속성을 사용하여 경계 상자의 색상과 크기를 변경할 수 있습니다.).
기본값: 1
labels
boolean
예측에 텍스트 레이블을 표시할지 여부. ( format 가 매개변수에 대해 입력 이미지를 선택하세요. 예측에는 모델 결과를 선택하세요. 선택적 구성 속성을 사용하여 경계 상자의 색상과 크기를 변경할 수 있습니다.).
기본값: false
format
string
옵션:
json: JSON 예측 배열을 반환합니다. (응답 형식 탭 참조).
image: 주석이 달린 예측이 포함된 이미지를 이진 블롭으로 반환하며 Content-Type 은 image/jpeg.
기본값: json
api_key
string
워크스페이스 API 설정 페이지에서 얻은 API 키
요청 본문
유형
설명
string
base64로 인코딩된 이미지. (쿼리 매개변수로 이미지 URL을 전달하지 않을 때 필요합니다).
콘텐츠 유형은 다음과 같아야 합니다 application/x-www-form-urlencoded 문자열 본문으로.
응답 형식
호스팅된 API 추론 엔드포인트와 대부분의 SDK는 다음을 반환합니다 JSON 예측 배열을 포함하는 객체입니다. 각 예측은 다음 속성을 가집니다:
x = 감지된 객체의 수평 중심점
y = 감지된 객체의 수직 중심점
width = 바운딩 박스의 너비
height = 바운딩 박스의 높이
class = 감지된 객체의 클래스 레이블
confidence = 감지된 객체가 올바른 레이블과 위치 좌표를 가질 확률(모델의 신뢰도)
다음은 REST API의 예시 응답 객체입니다:
The 매개변수에 대해 입력 이미지를 선택하세요. 예측에는 모델 결과를 선택하세요. 선택적 구성 속성을 사용하여 경계 상자의 색상과 크기를 변경할 수 있습니다. 속성은 추론을 위해 전송된 이미지의 높이와 너비를 포함합니다. 바운딩 박스 계산에 이 값을 사용해야 할 수 있습니다.
추론 API JSON 출력에서 박스 그리기
바운딩 박스를 렌더링하는 프레임워크와 패키지는 위치 형식이 다를 수 있습니다. 응답 JSON 객체의 속성을 고려하면, 다음 규칙들의 조합을 사용해 항상 바운딩 박스를 그릴 수 있습니다:
중심점은 항상 (x,y)
모서리 점들 (x1, y1) 이제 GPU TRT 컨테이너가 Docker에서 실행 중입니다. 다른 Ubuntu 터미널을 열어 Docker 컨테이너로 추론 데이터를 보낼 준비를 합니다. 다음을 사용하세요: (x2, y2) 는 다음을 사용해 찾을 수 있습니다:
x1 = x - (width/2)
y1 = y - (height/2)
x2 = x + (width/2)
y2 = y + (height/2)
모서리 점 접근 방식은 일반적인 패턴이며 다음과 같은 라이브러리에서 볼 수 있습니다 Pillow 을(를) 빌드할 때 box 객체는 이미지 내에서 바운딩 박스를 렌더링하기 위해 Image.
import UIKit
// 이미지 로드 및 Base64로 변환
let image = UIImage(named: "your-image-path") // 업로드할 이미지 경로 예: image.jpg
let imageData = image?.jpegData(compressionQuality: 1)
let fileContent = imageData?.base64EncodedString()
let postData = fileContent!.data(using: .utf8)
// API_KEY, 모델 및 모델 버전으로 추론 서버 요청 초기화
var request = URLRequest(url: URL(string: "https://detect.roboflow.com/your-model/your-model-version?api_key=YOUR_APIKEY&name=YOUR_IMAGE.jpg")!,timeoutInterval: Double.infinity)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
// POST 요청 실행
URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
// 응답을 문자열로 파싱
guard let data = data else {
print(String(describing: error))
return
}
// 응답 문자열을 사전으로 변환
do {
let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
// 문자열 응답 출력
print(String(data: data, encoding: .utf8)!)
}).resume()
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.StandardCharsets
import java.util.*
fun main() {
// 이미지 경로 가져오기
val filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "YOUR_IMAGE.jpg"
val file = File(filePath)
// Base64 인코딩
val encodedFile: String
val fileInputStreamReader = FileInputStream(file)
val bytes = ByteArray(file.length().toInt())
fileInputStreamReader.read(bytes)
encodedFile = String(Base64.getEncoder().encode(bytes), StandardCharsets.US_ASCII)
val API_KEY = "" // Your API Key
val MODEL_ENDPOINT = "dataset/v" // 모델 엔드포인트 설정 (Dataset URL에서 찾음)
// URL 구성
val uploadURL ="https://detect.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY + "&name=YOUR_IMAGE.jpg";
// HTTP 요청
var connection: HttpURLConnection? = null
try {
// URL에 대한 연결 구성
val url = URL(uploadURL)
connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded")
connection.setRequestProperty("Content-Length",
Integer.toString(encodedFile.toByteArray().size))
connection.setRequestProperty("Content-Language", "en-US")
connection.useCaches = false
connection.doOutput = true
// 요청 전송
val wr = DataOutputStream(
connection.outputStream)
wr.writeBytes(encodedFile)
wr.close()
// 응답 받기
val stream = connection.inputStream
val reader = BufferedReader(InputStreamReader(stream))
var line: String?
while (reader.readLine().also { line = it } != null) {
println(line)
}
reader.close()
} catch (e: Exception) {
e.printStackTrace()
} finally {
connection?.disconnect()
}
}
main()
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
fun main() {
val imageURL = "https://i.imgur.com/PEEvqPN.png" // 이미지 URL 교체
val API_KEY = "" // Your API Key
val MODEL_ENDPOINT = "dataset/v" // 모델 엔드포인트 설정
// 업로드 URL
val uploadURL = "https://detect.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY + "&image=" + URLEncoder.encode(imageURL, "utf-8");
// HTTP 요청
var connection: HttpURLConnection? = null
try {
// URL에 대한 연결 구성
val url = URL(uploadURL)
connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
connection.setRequestProperty("Content-Length", Integer.toString(uploadURL.toByteArray().size))
connection.setRequestProperty("Content-Language", "en-US")
connection.useCaches = false
connection.doOutput = true
// 요청 전송
val wr = DataOutputStream(connection.outputStream)
wr.writeBytes(uploadURL)
wr.close()
// 응답 받기
val stream = URL(uploadURL).openStream()
val reader = BufferedReader(InputStreamReader(stream))
var line: String?
while (reader.readLine().also { line = it } != null) {
println(line)
}
reader.close()
} catch (e: Exception) {
e.printStackTrace()
} finally {
connection?.disconnect()
}
}
main()
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class InferenceLocal {
public static void main(String[] args) throws IOException {
// 이미지 경로 가져오기
String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "YOUR_IMAGE.jpg";
File file = new File(filePath);
// Base64 인코딩
String encodedFile;
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStreamReader.read(bytes);
encodedFile = new String(Base64.getEncoder().encode(bytes), StandardCharsets.US_ASCII);
String API_KEY = ""; // Your API Key
String MODEL_ENDPOINT = "dataset/v"; // 모델 엔드포인트
// URL 구성
String uploadURL = "https://detect.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY
+ "&name=YOUR_IMAGE.jpg";
// HTTP 요청
HttpURLConnection connection = null;
try {
// URL에 대한 연결 구성
URL url = new URL(uploadURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(encodedFile.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
// 요청 전송
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(encodedFile);
wr.close();
// 응답 받기
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class InferenceHosted {
public static void main(String[] args) {
String imageURL = "https://i.imgur.com/PEEvqPN.png"; // 이미지 URL 교체
String API_KEY = ""; // Your API Key
String MODEL_ENDPOINT = "dataset/v"; // 모델 엔드포인트
// 업로드 URL
String uploadURL = "https://detect.roboflow.com/" + MODEL_ENDPOINT + "?api_key=" + API_KEY + "&image="
+ URLEncoder.encode(imageURL, StandardCharsets.UTF_8);
// HTTP 요청
HttpURLConnection connection = null;
try {
// URL에 대한 연결 구성
URL url = new URL(uploadURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(uploadURL.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
// 요청 전송
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(uploadURL);
wr.close();
// 응답 받기
InputStream stream = new URL(uploadURL).openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}