Sunday, 6 March 2022

How to convert video to gif using python opencv

 

 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
import cv2
from sklearn.metrics import mean_squared_error
from math import sqrt
import numpy as np
import traceback as tb
import images_to_gif as ig
from PIL import Image

cap = cv2.VideoCapture('..\\test\\videoplayback.mp4')
# Check if camera opened successfully
if (cap.isOpened()== False): 
  print("Error opening video  file")
farmes_list = list()
while(cap.isOpened()):
	ret, frame = cap.read()
	ret, frame = cap.read()
	if ret == True:
		# Display the resulting frame
		cv2.imshow('Frame', frame)
		farmes_list.append(frame)
	else:
		break
	# Press Q on keyboard to  exit
	if cv2.waitKey(25) & 0xFF == ord('q'):
		break

print(f'length of the frame list is= {len(farmes_list)}')
i = 0
new_frame = list()
for img in farmes_list:
	try:
		frame = img
		# Open image in bwDir - The searched image
		searchedImageBw = np.array(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
		# Open image to be compared
		inx = i
		if inx != len(farmes_list):
			cmpImage = np.array(cv2.cvtColor(farmes_list[inx+1], cv2.COLOR_BGR2GRAY))
			rms = sqrt(mean_squared_error(searchedImageBw, cmpImage))
			print(f'rms= {rms}')
			if rms>3:
				#farmes_list.remove(frame)
				new_frame.append(frame)


	except Exception as e:
		print(e)
		tb.print_exc()
		pass
	i = i+1
   

print(f'length of the frame list is= {len(new_frame)}')

pil_frame = [ Image.fromarray(img) for img in new_frame]
bytesio_object = ig.frame_gif(pil_frame)
ig.save(bytesio_object, path = "videotogif.gif")
cap.release()
cv2.destroyAllWindows()

Sunday, 23 January 2022

Fire off function without waiting for answer (Python)

Here is sample code for thread based method invocation additionally desired threading.stack_size can be added to boost the performance. Also its important to invoke Garbage collector if the number of threaded invocation is greater in number.
 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
import threading
import requests
import gc
#The stack size set by threading.stack_size is the amount of memory to allocate for the call stack in threads.
threading.stack_size(524288)

def alpha_gun(url, json, headers):
    #r=requests.post(url, data=json, headers=headers)
    r=requests.get(url)
    print(r.text)


def trigger(url, json, headers):
    threading.Thread(target=alpha_gun, args=(url, json, headers)).start()


url = "https://raw.githubusercontent.com/jyotiprakash-work/Live_Video_steaming/master/README.md"
payload="{}"
headers = {
  'Content-Type': 'application/json'
}

for i in range(10):
    print(i)
    #for condition 
    if i==5:
        trigger(url=url, json =payload, headers=headers)
        gc.collect()
        print('invoked')
    

Saturday, 22 January 2022

Face Recognition With python and face-net model

 Here i have added face recognition code in a flask app. The Face app contains registration, training model and recognition where each having a separate end point.




To access the endpoints please follow cUrls-

For Respiration- 
curl -X POST \
  http://127.0.0.1:5000/upload \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'postman-token: 2bf86477-f928-9ff2-d677-9b42a802e381' \
  -F file=@WIN_20220123_00_56_49_Pro.jpg \
  -F id=jp

For training-
curl -X POST \
  http://127.0.0.1:5000/train \
  -H 'cache-control: no-cache' \
  -H 'postman-token: 374826ca-15b5-7508-5052-f3ec43b1ca07'

For Recognition-
curl -X POST \
  http://127.0.0.1:5000/recognize \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'postman-token: 4183a550-5278-a7fe-c618-f100d164c7f8' \
  -F file=@WIN_20220123_00_57_28_Pro.jpg 

Sunday, 26 September 2021

Video Steaming python Websockets


#Server.py


import http.server as http
import asyncio
import websockets
import socketserver
import multiprocessing
import cv2
import sys
from datetime import datetime as dt

# Keep track of our generated processes
PROCESSES = []

def log(message):
    print("[LOG] " + str(dt.now()) + " - " + message)
#Feed function, here processing code feed can be placed
def camera(man):
    log("Starting camera")
    vc = cv2.VideoCapture(0)

    if vc.isOpened():
        r, f = vc.read()
    else:
        r = False

    while r:
        cv2.waitKey(20)
        r, f = vc.read()
        f = cv2.resize(f, (640, 480))
        encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 65]
        man[0] = cv2.imencode('.jpg', f, encode_param)[1]

# HTTP server handler
def server():
    server_address = ('0.0.0.0', 8000)
    if sys.version_info[1] < 7:
        class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.HTTPServer):
            pass
        httpd = ThreadingHTTPServer(server_address, http.SimpleHTTPRequestHandler)
    else:
        httpd = http.ThreadingHTTPServer(server_address, http.SimpleHTTPRequestHandler)
    log("Server started")
    httpd.serve_forever()

#Socket handler
def socket(man):
    # Will handle our websocket connections
    async def handler(websocket, path):
        log("Socket opened")
        try:
            while True:
                await asyncio.sleep(0.033) # 30 fps
                await websocket.send(man[0].tobytes())
        except websockets.exceptions.ConnectionClosed:
            log("Socket closed")

    log("Starting socket handler")
    # Create the awaitable object
    start_server = websockets.serve(ws_handler=handler, host='0.0.0.0', port=8585)
    # Start the server, add it to the event loop
    asyncio.get_event_loop().run_until_complete(start_server)
    # Registered our websocket connection handler, thus run event loop forever
    asyncio.get_event_loop().run_forever()


def main():
    manager = multiprocessing.Manager()
    lst = manager.list()
    lst.append(None)
    # Host the page, invoking server
    http_server = multiprocessing.Process(target=server)
    # Set up our websocket handler
    socket_handler = multiprocessing.Process(target=socket, args=(lst,))
    # Set up our camera-feed
    camera_handler = multiprocessing.Process(target=camera, args=(lst,))
    # Add 'em to our list
    PROCESSES.append(camera_handler)
    PROCESSES.append(http_server)
    PROCESSES.append(socket_handler)
    for p in PROCESSES:
        p.start()
    # Wait forever
    while True:
        pass

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        for p in PROCESSES:
            p.terminate()

#scripts.js

openSocket = () => {
    let uri = "ws://" + window.location.hostname + ":8585";
    socket = new WebSocket(uri);
    let msg = document.getElementById("msg");
    socket.addEventListener('open', (e) => {
        document.getElementById("status").innerHTML = "Opened";
    });
    socket.addEventListener('message', (e) => {
        let ctx = msg.getContext("2d");
        let image = new Image();
        image.src = URL.createObjectURL(e.data);
        image.addEventListener("load", (e) => {
            ctx.drawImage(image, 0, 0, msg.width, msg.height);
        });
    });
}
#index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Video Steam</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script type="text/javascript" src="script.js" ></script>
    </head>
    <body onload="openSocket()">
        <div id="status">
            Connection failed. May socket is broken.
        </div>
        <div style="text-align: center">
            <canvas id="msg" width="460" height="420" style="display:inline-block" />
        </div>
        
    </body>
</html>
Here is git link for full project.

Saturday, 20 June 2020

One way Live Video Steaming(Audio and Video) with Python Flask


Here in this code Both video and audio steaming is implemented. 
App.py holds the flask code for steaming and cemara.py contains
video capture method. download full code here

#APP.py

from flask import Flask, Response,render_template
import pyaudio
from camera import VideoCamera
import cv2

app = Flask(__name__)


FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 5


audio1 = pyaudio.PyAudio()



def genHeader(sampleRate, bitsPerSample, channels):
    datasize = 2000*10**6
    o = bytes("RIFF",'ascii')                                               # (4byte) Marks file as RIFF
    o += (datasize + 36).to_bytes(4,'little')                               # (4byte) File size in bytes excluding this and RIFF marker
    o += bytes("WAVE",'ascii')                                              # (4byte) File type
    o += bytes("fmt ",'ascii')                                              # (4byte) Format Chunk Marker
    o += (16).to_bytes(4,'little')                                          # (4byte) Length of above format data
    o += (1).to_bytes(2,'little')                                           # (2byte) Format type (1 - PCM)
    o += (channels).to_bytes(2,'little')                                    # (2byte)
    o += (sampleRate).to_bytes(4,'little')                                  # (4byte)
    o += (sampleRate * channels * bitsPerSample // 8).to_bytes(4,'little')  # (4byte)
    o += (channels * bitsPerSample // 8).to_bytes(2,'little')               # (2byte)
    o += (bitsPerSample).to_bytes(2,'little')                               # (2byte)
    o += bytes("data",'ascii')                                              # (4byte) Data Chunk Marker
    o += (datasize).to_bytes(4,'little')                                    # (4byte) Data size in bytes
    return o

@app.route('/audio')
def audio():
    # start Recording
    def sound():

        CHUNK = 1024
        sampleRate = 44100
        bitsPerSample = 16
        channels = 2
        wav_header = genHeader(sampleRate, bitsPerSample, channels)

        stream = audio1.open(format=FORMAT, channels=CHANNELS,
                        rate=RATE, input=True,input_device_index=1,
                        frames_per_buffer=CHUNK)
        print("recording...")
        #frames = []
        first_run = True
        while True:
           if first_run:
               data = wav_header + stream.read(CHUNK)
               first_run = False
           else:
               data = stream.read(CHUNK)
           yield(data)

    return Response(sound())

def gen(camera):
    while True:
        try:
            frame = camera.get_frame()
            yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
        except:
            frame = cv2.imread('loading.jpg')
            ret, jpeg = cv2.imencode('.jpg', frame)
            frame = jpeg.tobytes()
            yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('index.html')


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True, threaded=True,port=5000)
camera.py
import cv2
import imutils
import numpy as np
import time

ds_factor=0.6

#net = cv2.dnn.readNetFromCaffe('deploy.prototxt.txt', 'res10_300x300_ssd_iter_140000.caffemodel')

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)
    
    def __del__(self):
        self.video.release()
    
    def get_frame(self):
        success, image = self.video.read()
        #time.sleep(2.0)
        frame = image
        frame = imutils.resize(frame, width=400)
        (h, w) = frame.shape[:2]
        ret, jpeg = cv2.imencode('.jpg', frame)
        return jpeg.tobytes()

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style type="text/css">
    img {
  	display: block;
  	margin-left: auto;
  	margin-right: auto;
	width: 60%;
	height:60%;
	}
	div{
	display: block;
  	margin-left: auto;
  	margin-right: auto;
	width: 60%;
	height:60%; 
	}
    </style>
</head>
<body>
      <h1 align="center">Video Streaming Demonistration</h1>
    <img id="bg" class="center" src="{{ url_for('video_feed') }}">
    <div class="center">
    <audio style="width: 60%;" controls>
        <source src="{{ url_for('audio') }}" type="audio/x-wav;codec=pcm">
        Your browser does not support the audio element.
    </audio>
    </div>
</body>
</html>

Output


Friday, 29 May 2020

Remove Duplicates From a Python List




list_data = [1,1,2,2,2,3,4,5]

list_data = list(dict.fromkeys(list_data))
print(list_data)

list_data = ['a','a','b','c']
list_data = list(dict.fromkeys(list_data))
print(list_data)


Out Put

Saturday, 6 July 2019

Video to Image Converter using OpenCV Python

import cv2
import os

def video_to_frames(video, path_output_dir):
    # extract frames from a video and save to directory as 'x.png' where 
    # x is the frame index
    vidcap = cv2.VideoCapture(video)
    count = 0
    while vidcap.isOpened():
        success, image = vidcap.read()
        if success:
            cv2.imwrite(os.path.join(path_output_dir, '%d.png') % count, image)
            count += 1
        else:
            break
    cv2.destroyAllWindows()
    vidcap.release()

video_to_frames('VID_20190706_222120.mp4', './out')

OutPut Images








Sunday, 2 December 2018

Dynamic directory read and pickle example in python

import math
from sklearn import neighbors
import os
import os.path
import pickle
import glob
from PIL import Image, ImageDraw

nameL = []
name_indx = []
i = 0
X = []
y = []

dirName = glob.glob('data\\*\\')
for name in dirName:
 #print(glob.glob(name+'*.jpg'))
 v = os.path.dirname(name)
 print(v)
 nameL.append(v)
 name_indx.append(i)
 
 i = i+1
 imgs = glob.glob(name+'*.jpg')
 for img_path in imgs:
  print(img_path)
  X.append(img_path)
  
print(nameL)
print(name_indx)
dictionary = dict(zip(name_indx, nameL))
print(dictionary)
#pickling.........
pickle_out = open("dict.pickle","wb")
pickle.dump(dictionary, pickle_out)
pickle_out.close()

#Unpickling.......
pickle_in = open("dict.pickle","rb")
example_dict = pickle.load(pickle_in)
print(example_dict)
print(example_dict[1])

Tuesday, 6 November 2018

Extract text from image using Pytesseract in windows platform

For windows Os, we need an installation. Pytesseract binary is available here. Then Add a new variable with name tesseract in environment variables with value C:\Program Files (x86)\Tesseract-OCR\tesseract.exe

Then we need to install a python package: pip install tesseract 

Some cases we need the following line of code (if the environment variable is not added correctly) 

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe'


Here we provide the Pytesseract path to the interpreter.



Full Code

       
'''
download and install-https://github.com/UB-Mannheim/tesseract/wiki

'''

import numpy as np
import cv2
import time
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe'
frame1 = cv2.imread('poc.jpg',0);

cv2.imwrite('ocr.jpg',frame1)

#from tesseract import image_to_string
text = pytesseract.image_to_string(frame1)
print(text)
cv2.imshow(text,frame1 )

cv2.waitKey(0)
cv2.destroyAllWindows()



Input Image

Output






Saturday, 3 November 2018

ORB Feature matching Example in OpenCv

       

import cv2
import numpy as np
 
img1 = cv2.imread("face1.jpg", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("face2.jpg", cv2.IMREAD_GRAYSCALE)
 
# ORB Detector
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)
 
# Brute Force Matching
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key = lambda x:x.distance)
 
matching_result = cv2.drawMatches(img1, kp1, img2, kp2, matches[:50], None, flags=2)
 
cv2.imshow("Img1", img1)
cv2.imshow("Img2", img2)
cv2.imshow("Matching result", matching_result)
cv2.imwrite("Matching result.jpg", matching_result)
cv2.waitKey(0)
cv2.destroyAllWindows()


OutPut


Friday, 2 November 2018

Feature Descriptor like ORB, Shift and Surf Implementation using OpenCv Python

       
import cv2
import numpy as np
 
img = cv2.imread("2.PNG", cv2.IMREAD_GRAYSCALE)
 
sift = cv2.xfeatures2d.SIFT_create()
surf = cv2.xfeatures2d.SURF_create()
 
orb = cv2.ORB_create(nfeatures=1500)
# here None is for non-masking
keypoints1, descriptors1 = orb.detectAndCompute(img, None)
keypoints2, descriptors2 = sift.detectAndCompute(img, None)
keypoints3, descriptors3 = surf.detectAndCompute(img, None)
 
imgOrb  = cv2.drawKeypoints(img, keypoints1, None)
imgSift = cv2.drawKeypoints(img, keypoints2, None)
imgSurf = cv2.drawKeypoints(img, keypoints3, None)


cv2.imshow("Orb", cv2.resize(imgOrb,(700,500)) )
cv2.imshow("Sift", cv2.resize(imgSift,(700,500)) )
cv2.imshow("Surf", cv2.resize(imgSurf,(700,500)) )

cv2.waitKey(0)
cv2.destroyAllWindows()




OutPut


Friday, 19 October 2018

Capture Image by showing two finger to Camera using OpenCV python

You can find the code Here.

Here I use a binary classification model of SVM with rbf kernel. 

OutPut




Wednesday, 2 May 2018

Simple implementation of SVM in python

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
from sklearn import svm



#train set
x = [[86,105], [109, 100], [94, 105], [106, 100], [100, 100], 
     [80, 90], [103, 80], [105, 80], [120, 85], [77, 83], [92, 75], 
     [98, 76], [106, 82],[106, 77], [105, 77], [119, 80], [115, 70], 
     [110, 66], [105, 65], [90, 67], [80, 60], [90, 57], [105, 55],
     [115, 55], [110, 50], [109, 49], [95, 45], [100, 42], [105, 40],
     [110, 42], [115, 42], [115,35], [105, 35], [85, 35], [95, 35], [109, 35],
     [115, 35], [120, 30], [105, 29], [109, 25]]

#train set lebels
y = [130, 130, 130, 130, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120,
     120, 110, 110, 110, 110, 100, 100, 100, 100, 90, 90, 80, 80, 80, 80, 80, 70, 
     70, 60, 60, 60, 60, 50, 50, 40]
clf = svm.SVC(gamma=0.001, C=100)

clf.fit(x,y)

from sklearn.externals import joblib
joblib.dump(clf, 'C:/Users/kiit1/Desktop/svm.pkl')
test_set = [[86,105], [109, 100], [80, 90], [103, 80], [98, 76], [106, 82],
 [105, 77], [119, 80], [90, 57], [105, 55], [119, 27]]
y_test = [130, 130, 120, 123, 120, 120, 120, 120, 100, 100, 40]
# model accuracy for X_testaccuracy = clf.score(test_set, y_test)
print(clf.predict(test_set))
print(accuracy)

# creating a confusion matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, clf.predict(test_set))
print(cm)

clf1 = joblib.load('C:/Users/kiit1/Desktop/svm.pkl')
print(clf1.predict([[86,105]]))

Output

Sunday, 18 March 2018

Text separation using OpenCv python

       

import numpy as np
import time
import cv2

# Load an color image in grayscale
img = cv2.imread('1.PNG',0)
cv2.imshow('Realimage',img)
Img_height = np.size(img, 0)
Img_width = np.size(img, 1)
print(Img_height)
print("-----------------------------------------")
imgray = img
thresh = cv2.adaptiveThreshold(imgray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)#cv2.threshold(imgray,127,255,0)
im2, contours, hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0,255,0), 3)
#cnt = contours[4]
for cnt in contours:
 #cv2.drawContours(img, [cnt], 0, (128,255,0), 2)
 x,y,w,h = cv2.boundingRect(cnt)
 img =cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
 crop_img = img[y:y+h, x:x+w]
 height_sub = np.size(crop_img, 0)
 width_sub = np.size(crop_img, 1)
 print(height_sub)
 if Img_height/2 <height_sub and Img_width/2 > width_sub:
     cv2.imwrite('./dataIMG/'+ str(time.time())+'.png',crop_img)
 
cv2.imshow('image',imgray)

cv2.waitKey(0)
cv2.destroyAllWindows()




Input

Output







Wednesday, 17 May 2017

Eye and Face detection in Opencv 3.0 java

       
package opencvImpl;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.video.Video;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;

import opencvImpl.view.ImageViewer;
import opencvImpl.view.VideoViewer;

public class VideoTest {
 static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
public static void main(String args[]){
 VideoViewer videoViewer=new VideoViewer();
 videoViewer.createJFrame("sky");
 Mat matImg=new Mat();
 VideoCapture videoCapture=new VideoCapture(0);
 videoCapture.set(Videoio.CAP_PROP_FRAME_WIDTH, 1120);
 videoCapture.set(Videoio.CAP_PROP_FRAME_HEIGHT, 840);
 if(videoCapture.isOpened()){
  CascadeClassifier facedectector=new CascadeClassifier("D:/IMGprocesingOpenCV/opencvv3/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml");
  CascadeClassifier eyedetecter=new CascadeClassifier("D:/IMGprocesingOpenCV/opencvv3/opencv/sources/data/haarcascades/haarcascade_eye.xml");
  CascadeClassifier smiledetecter=new CascadeClassifier("D:/IMGprocesingOpenCV/opencvv3/opencv/sources/data/haarcascades/haarcascade_smile.xml");
  MatOfRect faceDetections = new MatOfRect();
  MatOfRect eyeDetections = new MatOfRect();
  MatOfRect smileDetections = new MatOfRect();
  while(true){
   videoCapture.read(matImg);
   facedectector.detectMultiScale(matImg, faceDetections);
   for(Rect rect:faceDetections.toArray()){
   Imgproc.rectangle(matImg, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
      
   }
   eyedetecter.detectMultiScale(matImg, eyeDetections);
   for(Rect rect:eyeDetections.toArray()){
    Imgproc.rectangle(matImg, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
       
    }
//   smiledetecter.detectMultiScale(matImg, smileDetections);
//   for(Rect rect:smileDetections.toArray()){
//    Imgproc.rectangle(matImg, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
//       
//    }
   videoViewer.show(matImg);
   
   
  }
 }else {
  System.out.println("Err in CAMERA IO");
 }
}
}


package opencvImpl.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;

import org.opencv.core.Mat;

public class VideoViewer {
 private JLabel imageView;
 public void show(Mat image){
 show(image, "");
 }
 public void show(Mat image,String windowName){
 setSystemLookAndFeel();
// JFrame frame = createJFrame(windowName);
 Image loadedImage = toBufferedImage(image);
 imageView.setIcon(new ImageIcon(loadedImage));
// frame.pack();
// frame.setLocationRelativeTo(null);
// frame.setVisible(true);
 }
 public JFrame createJFrame(String windowName) {
 JFrame frame = new JFrame(windowName);
 imageView = new JLabel();
 final JScrollPane imageScrollPane = new JScrollPane(imageView);
 imageScrollPane.setPreferredSize(new Dimension(640, 480));
 frame.add(imageScrollPane, BorderLayout.CENTER);
 frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 frame.pack();
 frame.setLocationRelativeTo(null);
  frame.setVisible(true);
 return frame;
 }
 private void setSystemLookAndFeel() {
 try {
 UIManager.setLookAndFeel
 (UIManager.getSystemLookAndFeelClassName());
 } catch (ClassNotFoundException e) {
 e.printStackTrace();
 } catch (InstantiationException e) {
 e.printStackTrace();
 } catch (IllegalAccessException e) {
 e.printStackTrace();
 } catch (UnsupportedLookAndFeelException e) {
 e.printStackTrace();
 }
 }
 public Image toBufferedImage(Mat matrix){
 int type = BufferedImage.TYPE_BYTE_GRAY;
 if ( matrix.channels() > 1 ) {
 type = BufferedImage.TYPE_3BYTE_BGR;
 }
 int bufferSize = matrix.channels()*matrix.cols()*matrix.rows();
 byte [] buffer = new byte[bufferSize];
 matrix.get(0,0,buffer); // get all the pixels
 BufferedImage image = new BufferedImage(matrix.cols(),matrix.
 rows(), type);
 final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
 System.arraycopy(buffer, 0, targetPixels, 0, buffer.length);
 return image;
 }
 
}

 

OutPut