File size: 2,445 Bytes
2880d52
6e2e3a9
2880d52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from matplotlib.patches import Rectangle
from describe import process_image
import matplotlib.pyplot as plt
from PIL import Image
import ocrmac
import json
import time
import cv2
import os

time.sleep(2)

with open('pwd.txt', 'r') as pwd:
    folder_location = pwd.read()


def crop_and_save_image(img, box, output_path):

    # Convert box coordinates to integers
    box = [int(coord) for coord in box]

    # Crop the image to the specified region of interest
    cropped_img = img[box[1]:box[3], box[0]:box[2]]
    cv2.imwrite(output_path, cropped_img)


def visualize_result(image_file_path, result):
    assert isinstance(result, list)

    og_img = cv2.imread(image_file_path)
    img = cv2.imread(image_file_path)

    captions = []

    for r in result:
        box = r['box']
        caption = r['cap']
        if "<unk>" in caption:
            crop_and_save_image(og_img, box, "ocr.png")
            recognized = ocrmac.OCR('Sample Images/Image.jpeg').recognize()
            caption = caption.replace("<unk>", recognized[0][0])
        cv2.rectangle(img, (int(box[0]), int(box[1])),
                      (int(box[2]), int(box[3])), (0, 0, 255), 2)
        cv2.rectangle(img, (int(box[0]), int(box[1])), (int(
            box[2]), int(box[1])-50), (200, 200, 200), -1)
        cv2.rectangle(img, (int(box[0]), int(box[1])),
                      (int(box[2]), int(box[1])-50), (0, 0, 0), 2)
        cv2.putText(img, caption, (int(box[0]), int(
            box[1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
        captions.append(caption)

    cv2.imwrite("output.png", img)

    return captions, img


def describe_image(frame):
    IMG_FILE_PATH = f'{folder_location}image.png'

    cv2.imwrite(IMG_FILE_PATH, frame)
    process_image(IMG_FILE_PATH, folder_location)

    RESULT_JSON_PATH = f'{folder_location}CircumSpect/result.json'
    with open(RESULT_JSON_PATH, 'r') as f:
        results = json.load(f)

    TO_K = 10
    assert IMG_FILE_PATH in results.keys()
    captions, frame = visualize_result(
        IMG_FILE_PATH, results[IMG_FILE_PATH][:TO_K])

    return captions, frame

if __name__ == "__main__":
    cap = cv2.VideoCapture(0)
    time.sleep(2)
    start = time.time()
    while True:
        end = time.time()
        print(end-start)
        _, img = cap.read()
        caption, frame = describe_image(img)
        cv2.imshow("CircumSpect", frame)
        cv2.waitKey(1)
        start = time.time()