dahyedahye commited on
Commit
2d8a39b
·
1 Parent(s): c216f77
Files changed (2) hide show
  1. app.py +18 -65
  2. app.py.bacup2 +81 -0
app.py CHANGED
@@ -1,11 +1,8 @@
1
- import io
2
  import cv2
3
  import numpy as np
4
- import base64
5
- from PIL import Image
6
- from fastapi import FastAPI, HTTPException
7
- from fastapi.responses import StreamingResponse, JSONResponse
8
- from pydantic import BaseModel
9
 
10
  app = FastAPI(
11
  version="0.0.1",
@@ -17,65 +14,21 @@ app = FastAPI(
17
  ],
18
  )
19
 
20
- # Pydantic 모델 정의
21
- class ImageData(BaseModel):
22
- image_base64: str
23
-
24
- @app.post("/process-image/")
25
- def process_image(data: ImageData):
26
- try:
27
- # Base64 문자열을 디코딩하여 이미지 데이터를 생성
28
- image_data = base64.b64decode(data.image_base64)
29
- # NumPy 배열로 변환
30
- nparr = np.frombuffer(image_data, np.uint8)
31
- # OpenCV를 사용하여 이미지 디코딩
32
- image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
33
-
34
- if image is None:
35
- raise HTTPException(status_code=400, detail="Invalid image data")
36
-
37
- # 그레이스케일로 변환
38
- gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
39
-
40
- # Canny 에지 검출 적용
41
- edges = cv2.Canny(gray_image, threshold1=100, threshold2=200)
42
- edges_image = Image.fromarray(edges)
43
-
44
- # 흰색 배경 생성
45
- white_background = Image.new("RGB", edges_image.size, (255, 255, 255))
46
-
47
- # 검은색 에지를 흰색 배경 위에 합성
48
- edges_on_white = Image.composite(Image.new("RGB", edges_image.size, (0, 0, 0)), white_background, edges_image)
49
-
50
- # 최종 Canny 이미지를 BytesIO 객체에 저장
51
- canny_output_io = io.BytesIO()
52
- edges_on_white.save(canny_output_io, format='JPEG')
53
- canny_output_io.seek(0)
54
-
55
- # Sobel 연산자 적용
56
- sobelx = cv2.Sobel(gray_image, cv2.CV_64F, 1, 0, ksize=5) # X 축에 대한 Sobel 연산자
57
- sobely = cv2.Sobel(gray_image, cv2.CV_64F, 0, 1, ksize=5) # Y 축에 대한 Sobel 연산자
58
-
59
- # 두 기울기 결합
60
- sobel_combined = cv2.magnitude(sobelx, sobely)
61
-
62
- # 결과를 [0, 255] 범위로 정규화
63
- sobel_combined = cv2.normalize(sobel_combined, None, 0, 255, cv2.NORM_MINMAX)
64
- sobel_combined = sobel_combined.astype('uint8')
65
-
66
- # 결과를 PIL 이미지로 변환
67
- sobel_image = Image.fromarray(sobel_combined)
68
-
69
- # Sobel 에지를 흰색 배경 위에 합성
70
- edges_on_white_sobel = Image.composite(Image.new("RGB", sobel_image.size, (0, 0, 0)), white_background, sobel_image)
71
 
72
- # 최종 Sobel 이미지를 BytesIO 객체에 저장
73
- sobel_output_io = io.BytesIO()
74
- edges_on_white_sobel.save(sobel_output_io, format='JPEG')
75
- sobel_output_io.seek(0)
76
 
77
- # StreamingResponse를 사용하여 파일 반환
78
- return StreamingResponse(sobel_output_io, media_type='image/jpeg')
 
79
 
80
- except Exception as e:
81
- return JSONResponse(status_code=500, content={"message": str(e)})
 
1
+ from fastapi import FastAPI, File, UploadFile
2
  import cv2
3
  import numpy as np
4
+ from fastapi.responses import StreamingResponse
5
+ import io
 
 
 
6
 
7
  app = FastAPI(
8
  version="0.0.1",
 
14
  ],
15
  )
16
 
17
+ @app.post("/detect-edges/")
18
+ async def detect_edges(file: UploadFile = File(...)):
19
+ # 이미지를 바이트 배열로 읽기
20
+ image_bytes = await file.read()
21
+ # 바이트 배열을 numpy 배열로 변환
22
+ nparr = np.frombuffer(image_bytes, np.uint8)
23
+ # numpy 배열을 이미지로 디코딩
24
+ img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ # 엣지 디텍션 수행 (Canny 알고리즘 사용)
27
+ edges = cv2.Canny(img, 100, 200)
 
 
28
 
29
+ # 엣지 이미지를 다시 인코딩
30
+ _, buffer = cv2.imencode('.png', edges)
31
+ io_buf = io.BytesIO(buffer)
32
 
33
+ # 결과 이미지를 사용자에게 전송
34
+ return StreamingResponse(io_buf, media_type="image/png")
app.py.bacup2 ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import cv2
3
+ import numpy as np
4
+ import base64
5
+ from PIL import Image
6
+ from fastapi import FastAPI, HTTPException
7
+ from fastapi.responses import StreamingResponse, JSONResponse
8
+ from pydantic import BaseModel
9
+
10
+ app = FastAPI(
11
+ version="0.0.1",
12
+ servers=[
13
+ {
14
+ "url": "https://leekwoon-edge-api.hf.space",
15
+ "description": "image edge detection API",
16
+ }
17
+ ],
18
+ )
19
+
20
+ # Pydantic 모델 정의
21
+ class ImageData(BaseModel):
22
+ image_base64: str
23
+
24
+ @app.post("/process-image/")
25
+ def process_image(data: ImageData):
26
+ try:
27
+ # Base64 문자열을 디코딩하여 이미지 데이터를 생성
28
+ image_data = base64.b64decode(data.image_base64)
29
+ # NumPy 배열로 변환
30
+ nparr = np.frombuffer(image_data, np.uint8)
31
+ # OpenCV를 사용하여 이미지 디코딩
32
+ image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
33
+
34
+ if image is None:
35
+ raise HTTPException(status_code=400, detail="Invalid image data")
36
+
37
+ # 그레이스케일로 변환
38
+ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
39
+
40
+ # Canny 에지 검출 적용
41
+ edges = cv2.Canny(gray_image, threshold1=100, threshold2=200)
42
+ edges_image = Image.fromarray(edges)
43
+
44
+ # 흰색 배경 생성
45
+ white_background = Image.new("RGB", edges_image.size, (255, 255, 255))
46
+
47
+ # 검은색 에지를 흰색 배경 위에 합성
48
+ edges_on_white = Image.composite(Image.new("RGB", edges_image.size, (0, 0, 0)), white_background, edges_image)
49
+
50
+ # 최종 Canny 이미지를 BytesIO 객체에 저장
51
+ canny_output_io = io.BytesIO()
52
+ edges_on_white.save(canny_output_io, format='JPEG')
53
+ canny_output_io.seek(0)
54
+
55
+ # Sobel 연산자 적용
56
+ sobelx = cv2.Sobel(gray_image, cv2.CV_64F, 1, 0, ksize=5) # X 축에 대한 Sobel 연산자
57
+ sobely = cv2.Sobel(gray_image, cv2.CV_64F, 0, 1, ksize=5) # Y 축에 대한 Sobel 연산자
58
+
59
+ # 두 기울기 결합
60
+ sobel_combined = cv2.magnitude(sobelx, sobely)
61
+
62
+ # 결과를 [0, 255] 범위로 정규화
63
+ sobel_combined = cv2.normalize(sobel_combined, None, 0, 255, cv2.NORM_MINMAX)
64
+ sobel_combined = sobel_combined.astype('uint8')
65
+
66
+ # 결과를 PIL 이미지로 변환
67
+ sobel_image = Image.fromarray(sobel_combined)
68
+
69
+ # Sobel 에지를 흰색 배경 위에 합성
70
+ edges_on_white_sobel = Image.composite(Image.new("RGB", sobel_image.size, (0, 0, 0)), white_background, sobel_image)
71
+
72
+ # 최종 Sobel 이미지를 BytesIO 객체에 저장
73
+ sobel_output_io = io.BytesIO()
74
+ edges_on_white_sobel.save(sobel_output_io, format='JPEG')
75
+ sobel_output_io.seek(0)
76
+
77
+ # StreamingResponse를 사용하여 파일 반환
78
+ return StreamingResponse(sobel_output_io, media_type='image/jpeg')
79
+
80
+ except Exception as e:
81
+ return JSONResponse(status_code=500, content={"message": str(e)})