Thursday, 12 January 2023

 Buffer Data Into Image Using Memcopy-OpenCV

 Buffer Data Convert as Image Using OpenCV


                                          Code
Code version v0.1
---------------------------------------------------------------------------------------------------------------------------


#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>

HANDLE hSlot;
LPCTSTR SlotName = TEXT("\\\\.\\mailslot\\mailslot");

BOOL ReadSlot()
{
    DWORD cbMessage, cMessage, cbRead;
    BOOL fResult;
    LPTSTR lpszBuffer;
    TCHAR achID[80];
    DWORD cAllMessages;
    HANDLE hEvent;
    OVERLAPPED ov;

    cbMessage = cMessage = cbRead = 0;

    hEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("ExampleSlot"));
    if (NULL == hEvent)
        return FALSE;
    ov.Offset = 0;
    ov.OffsetHigh = 0;
    ov.hEvent = hEvent;

    fResult = GetMailslotInfo(hSlot, // mailslot handle
        (LPDWORD)NULL,               // no maximum message size
        &cbMessage,                   // size of next message
        &cMessage,                    // number of messages
        (LPDWORD)NULL);              // no read time-out

    if (!fResult)
    {
        printf("GetMailslotInfo failed with %d.\n", GetLastError());
        return FALSE;
    }

    if (cbMessage == MAILSLOT_NO_MESSAGE)
    {
        printf("Waiting for a message...\n");
        return TRUE;
    }

    cAllMessages = cMessage;

    while (cMessage != 0)  // retrieve all messages
    {
        // Allocate memory for the message.

        lpszBuffer = (LPTSTR)GlobalAlloc(GPTR,
            lstrlen((LPTSTR)achID) * sizeof(TCHAR) + cbMessage);
        if (NULL == lpszBuffer)
            return FALSE;
        lpszBuffer[0] = '\0';

        fResult = ReadFile(hSlot,
            lpszBuffer,
            cbMessage,
            &cbRead,
            &ov);

        if (!fResult)
        {
            printf("ReadFile failed with %d.\n", GetLastError());
            GlobalFree((HGLOBAL)lpszBuffer);
            return FALSE;
        }
        cv::Mat mat = cv::Mat(640, 640, CV_8UC3, cv::Scalar(0, 0, 0));
        std::memcpy(mat.data, lpszBuffer, 640 * 640 * 3);
      
        cv::imshow("YOURWINDOW", mat);
        cv::waitKey(1);

        GlobalFree((HGLOBAL)lpszBuffer);

        fResult = GetMailslotInfo(hSlot,  // mailslot handle
            (LPDWORD)NULL,               // no maximum message size
            &cbMessage,                   // size of next message
            &cMessage,                    // number of messages
            (LPDWORD)NULL);              // no read time-out

        if (!fResult)
        {
            printf("GetMailslotInfo failed (%d)\n", GetLastError());
            return FALSE;
        }
    }
    CloseHandle(hEvent);
    return TRUE;
}


BOOL WINAPI MakeSlot(LPCTSTR lpszSlotName)
{
    hSlot = CreateMailslot(
        lpszSlotName,
        0,
        MAILSLOT_WAIT_FOREVER,
        (LPSECURITY_ATTRIBUTES)NULL);

    if (hSlot == INVALID_HANDLE_VALUE) {
        printf("CreateMailslot failed with %d\n", GetLastError());
        return FALSE;
    }
    else
        std::cout << "Mailslot created successfully.\n";
    return TRUE;
}

int main()
{
    MakeSlot(SlotName);


    cv::namedWindow("YOURWINDOW", cv::WINDOW_AUTOSIZE);
    while (true) {
        ReadSlot();
    }
}

// producer:

LPCTSTR SlotName = TEXT("\\\\.\\mailslot\\mailslot");

BOOL WriteSlot(HANDLE hSlot, LPCTSTR lpszMessage)
{
    BOOL fResult;
    DWORD cbWritten;

    fResult = WriteFile(hSlot, lpszMessage,
                (DWORD)(lstrlen(lpszMessage) + 1) * sizeof(TCHAR),
                &cbWritten, (LPOVERLAPPED)NULL);

    if (!fResult) {
        printf("WriteFile failed with %d.\n", GetLastError());
        return FALSE;
    }

    printf("Slot written to successfully.\n");

    return TRUE;
}
cv::Mat mat =
        cv::imread("C:\\Repos\\tmp\\decode\\images\\output_0664.jpg");
            size_t sizeInBytes = mat.step[0] * mat.rows;

            LPVOID lpBuffer = malloc(sizeInBytes);

            HANDLE hFile;

            hFile = CreateFile(SlotName, GENERIC_WRITE,
                       FILE_SHARE_READ,
                       (LPSECURITY_ATTRIBUTES)NULL,
                       OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
                       (HANDLE)NULL);

            if (hFile == INVALID_HANDLE_VALUE) {
                printf("CreateFile failed with %d.\n",
                       GetLastError());
                return FALSE;
            }
            DWORD bytesWritten;
            memcpy(lpBuffer, &mat.data[0], sizeInBytes);

            WriteFile(hFile, lpBuffer, sizeInBytes, &bytesWritten,
                  NULL);

            CloseHandle(hFile);
 
 
 
 
 
Code Version V0.2:
-----------------------------------------------------------------------------------------------


#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>

HANDLE hSlot;
LPCTSTR SlotName = TEXT("\\\\.\\mailslot\\mailslot");

BOOL ReadSlot()
{
    DWORD cbMessage, cMessage, cbRead;
    BOOL fResult;
    LPTSTR lpszBuffer;
    TCHAR achID[80];
    DWORD cAllMessages;
    HANDLE hEvent;
    OVERLAPPED ov;

    cbMessage = cMessage = cbRead = 0;

    hEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("ExampleSlot"));
    if (NULL == hEvent)
        return FALSE;
    ov.Offset = 0;
    ov.OffsetHigh = 0;
    ov.hEvent = hEvent;

    fResult = GetMailslotInfo(hSlot, // mailslot handle
        (LPDWORD)NULL,               // no maximum message size
        &cbMessage,                   // size of next message
        &cMessage,                    // number of messages
        (LPDWORD)NULL);              // no read time-out

    if (!fResult)
    {
        printf("GetMailslotInfo failed with %d.\n", GetLastError());
        return FALSE;
    }

    if (cbMessage == MAILSLOT_NO_MESSAGE)
    {
        printf("Waiting for a message...\n");
        return TRUE;
    }

    cAllMessages = cMessage;

    while (cMessage != 0)  // retrieve all messages
    {
        // Allocate memory for the message.

        lpszBuffer = (LPTSTR)GlobalAlloc(GPTR,
            lstrlen((LPTSTR)achID) * sizeof(TCHAR) + cbMessage);
        if (NULL == lpszBuffer)
            return FALSE;
        lpszBuffer[0] = '\0';

        fResult = ReadFile(hSlot,
            lpszBuffer,
            cbMessage,
            &cbRead,
            &ov);

        if (!fResult)
        {
            printf("ReadFile failed with %d.\n", GetLastError());
            GlobalFree((HGLOBAL)lpszBuffer);
            return FALSE;
        }
        cv::Mat mat = cv::Mat(640, 640, CV_8UC3, cv::Scalar(0, 0, 0));
        std::memcpy(mat.data, lpszBuffer, 640 * 640 * 3);
      
        cv::imshow("YOURWINDOW", mat);
        cv::waitKey(1);

        GlobalFree((HGLOBAL)lpszBuffer);

        fResult = GetMailslotInfo(hSlot,  // mailslot handle
            (LPDWORD)NULL,               // no maximum message size
            &cbMessage,                   // size of next message
            &cMessage,                    // number of messages
            (LPDWORD)NULL);              // no read time-out

        if (!fResult)
        {
            printf("GetMailslotInfo failed (%d)\n", GetLastError());
            return FALSE;
        }
    }
    CloseHandle(hEvent);
    return TRUE;
}


BOOL WINAPI MakeSlot(LPCTSTR lpszSlotName)
{
    hSlot = CreateMailslot(
        lpszSlotName,
        0,
        MAILSLOT_WAIT_FOREVER,
        (LPSECURITY_ATTRIBUTES)NULL);

    if (hSlot == INVALID_HANDLE_VALUE) {
        printf("CreateMailslot failed with %d\n", GetLastError());
        return FALSE;
    }
    else
        std::cout << "Mailslot created successfully.\n";
    return TRUE;
}

int main()
{
    MakeSlot(SlotName);


    cv::namedWindow("YOURWINDOW", cv::WINDOW_AUTOSIZE);
    while (true) {
        ReadSlot();
    }
}

// producer:

LPCTSTR SlotName = TEXT("\\\\.\\mailslot\\mailslot");

BOOL WriteSlot(HANDLE hSlot, LPCTSTR lpszMessage)
{
    BOOL fResult;
    DWORD cbWritten;

    fResult = WriteFile(hSlot, lpszMessage,
                (DWORD)(lstrlen(lpszMessage) + 1) * sizeof(TCHAR),
                &cbWritten, (LPOVERLAPPED)NULL);

    if (!fResult) {
        printf("WriteFile failed with %d.\n", GetLastError());
        return FALSE;
    }

    printf("Slot written to successfully.\n");

    return TRUE;
}
cv::Mat mat =
        cv::imread("C:\\Repos\\tmp\\decode\\images\\output_0664.jpg");
            size_t sizeInBytes = mat.step[0] * mat.rows;

            LPVOID lpBuffer = malloc(sizeInBytes);

            HANDLE hFile;

            hFile = CreateFile(SlotName, GENERIC_WRITE,
                       FILE_SHARE_READ,
                       (LPSECURITY_ATTRIBUTES)NULL,
                       OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
                       (HANDLE)NULL);

            if (hFile == INVALID_HANDLE_VALUE) {
                printf("CreateFile failed with %d.\n",
                       GetLastError());
                return FALSE;
            }
            DWORD bytesWritten;
            memcpy(lpBuffer, &mat.data[0], sizeInBytes);

            WriteFile(hFile, lpBuffer, sizeInBytes, &bytesWritten,
                  NULL);

            CloseHandle(hFile); 
 
 
 

Tuesday, 26 January 2021

Image Instant Segmentation:

                  Image Instant Segmentation


Image Segmentation instantly with 3 Line of codes:

Image Segmentation:


import pixellib

from pixellib.semantic import semantic_segmentation

import cv2


segment_image = semantic_segmentation()

segment_image.load_pascalvoc_model("pascal.h5")

output, segmap = segment_image.segmentAsPascalvoc("Testimage.jpg")

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

print(output.shape)

step 2:

        

import pixellib

from pixellib.semantic import semantic_segmentation

import cv2


segment_image = semantic_segmentation()

segment_image.load_pascalvoc_model("pascal.h5")

segmap, segoverlay = segment_image.segmentAsPascalvoc("Testimage.jpg", overlay= True)

cv2.imwrite("img.jpg", segoverlay)

print(segoverlay.shape)


Mask r-cnn:

code:

import pixellib

from pixellib.instance import instance_segmentation

segment_image = instance_segmentation()

segment_image.load_model("mask_rcnn_coco.h5") 

segment_image.segmentImage("path_to_image", output_image_name = "output_image_path")


Step 2:

import pixellib

from pixellib.instance import instance_segmentation

import cv2


instance_seg = instance_segmentation()

instance_seg.load_model("mask_rcnn_coco.h5")

segmask, output = instance_seg.segmentImage("sample2.jpg")

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

print(output.shape)



Installation Prcoedure:

1.Python 3.6

2.pixellib

3.Openc 3.4.12






Tuesday, 25 February 2020

DICOM2VIDEO

                                                                                                            DICOM2VIDEO

Source Code 

Main file:

import numpy as np
from cv2 import VideoWriter, VideoWriter_fourcc
import os
import glob
import cv2
from pprint import pprint
import sys,os
from datetime import datetime
import dcminout_root
import datetime

strt_time = datetime.datetime.now()
print(strt_time)
# width = 300
# height = 300
#FPS = 24
#seconds = 10
FPS =10
seconds =10
# var='nb'
var = sys.argv[1]
re=dcminout_root.inout_root(var)
files=re[4]
file_count = files
# tot=file_count-1
# start_n=tot/2
# if type(start_n)==float:
#     startn=np.ceil(start_n)
#     var_mul_str=startn*0.6
#     var_mul_str=np.ceil(var_mul_str)
#     endn=np.floor(start_n)
#     var_mul_end=endn*0.6
#     var_mul_end=np.ceil(var_mul_end)  

# else:
 
#     startn=np.ceil(start_n)
#     endn=np.ceil(start_n)
#     var_mul_str=startn*0.6
#     var_mul_end=endn*0.6

    # print(start_n,endn)


def color_gray(var):

    rt=var
 
    # rt='var'
    dcm=dcminout_root.inout_root(rt)
    # indir=data[0]
    # input_dir=indir["dicom_dir"]
    input_dir=dcm[0]
    # oudir=data[1]
    # output_dir=oudir["out_dir"]
    output_dir=dcm[1]
    videoheight=dcm[2]
    videoheight=int(videoheight)

 
 

    videowidth=dcm[3]
    videowidth=int(videowidth)
    # dcm_len=dcm[4]
    # video_direction=dcm[4]

    # dcmaxis_dir=dcm[5]
    # dcmdecimal_val=dcm[6]
    # actl_center=dcm[7]
    # actl_center=int(actl_center)
    # end_val=dcm[8]
    # end_val=int(end_val)
    # print(dcmaxis_dir,dcmdecimal_val)
    # video_direction=str(video_direction)
    # slids_incval=dcm[5]
    # # videowidth=videowidth["Video_widh"]
    # fourcc = VideoWriter_fourcc(*'MP4v')
    out_videoname=dcm[9]
    video_outputname=output_dir+"/"+out_videoname+'.mp4'
    video_out = os.path.join(output_dir, video_outputname)
################################################################################################
 
    data_path = os.path.join(input_dir, '*jpg')
    files = glob.glob(data_path)
    RGB=[]
    # dr=dcmaxis_dir
    # if dr=='x':
    #         # print('x')
           
    #     framx='x-axis='
    #     framy='y-axis=NA'
    #     framz='z-axis=NA'

    #     cv2.putText(RGB, framx+str(xr), (width-650, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),3)
    #     cv2.putText(RGB, framy, (width-650, 103), cv2.FONT_HERSHEY_SIMPLEX,2, (0, 0, 255),3)
    #     cv2.putText(RGB, framz, (width-650, 158), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),3)
    # elif dr=='y':
    #     # print('y')
    #     framx='x-axis=NA'
    #     framy='y-axis='
    #     framz='z-axis=NA'
    #     cv2.putText(RGB, framx, (width-650, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),3)
    #     cv2.putText(RGB, framy+str(xr), (width-650, 103), cv2.FONT_HERSHEY_SIMPLEX,2, (0, 0, 255),3)
    #     cv2.putText(RGB, framz, (width-650, 158), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),3)
    # else:
    #     # print('z')
    #     framx='x-axis=NA'
    #     framy='y-axis=NA'
    #     framz='z-axis='
    #     cv2.putText(RGB, framx, (width-650, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),3)
    #     cv2.putText(RGB, framy, (width-650, 103), cv2.FONT_HERSHEY_SIMPLEX,2, (0, 0, 255),3)
    #     cv2.putText(RGB, framz+str(xr), (width-650, 158), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),3)
 
    files =  glob.glob(data_path)
    file_count = len(files)
 
    # framx='x-axis='
    # framy='y-axis=NA'
    # framz='z-axis=NA'
    # Unit='   unit=mm'
    # img_array = []
    out = cv2.VideoWriter(video_out,cv2.VideoWriter_fourcc(*'DIVX'), float(FPS), (videowidth,videoheight))
    # out = cv2.VideoWriter(video_out,cv2.VideoWriter_fourcc(*'DIVX'), float(FPS), (4000,2588))
    # mn=float(dcmdecimal_val)
 
    # ########### SHORT CUT FOR 0.6 CODE
    # tot=file_count-1
    # # ovl_ln=tot*mn  ##0.6
    # # half_ln=ovl_ln/2
    # # ### for this below code for center based will change
    # # # actl_center=1465  ## for z direction2041  ##35
    # # actl_center=2041  ## for z direction2041  ##35

    # # start_val=actl_center-1
    # # # end_val=7869-actl_center ## 2630 ##100  x
    # # end_val=3573-actl_center ## 2630 ##100
    # # cc=start_val
    # # vv=end_val
    # ## By Changes '0' Center variation 0.6 from left and right  May 21
    # LN=actl_center
    # LNend=LN*mn
    # RP=file_count-actl_center
    # RPend=RP*mn
    # lxr=[]
    # LNend=round(LNend,1)
    # for l in np.arange(-LNend,0,mn):
    #     # rx=round(r,1)
    #     lx=round(l,2)
    #     lxr.append(lx)
    # # print(lxr)
    # RPend=round(RPend,1)
    # for r in np.arange(0,RPend,mn):
    #     rx=round(r,1)
    #     lxr.append(rx)
    # print(lxr)
    # print(len(lxr))
    # print(lxr)
    # import fram_decimal
    # res=fram_decimal.fram_dcml(actl_center,file_count,mn)
    for f1 in sorted(files):
        # for f1,xx in zip(sorted(files),lxr):
    # for f1,xx in zip(sorted(files),np.arange(-1*np.int(cc),np.int(vv),mn)):
    # for f1,xx in zip(sorted(files),np.arange(-1*np.int(half_ln),np.int(half_ln),0.6)):  
        # xr=round(xx,1)
        # xr=np.array(xr)
        # print(xr)
        # print(xr)  
        # print(new)    
    # for xn in range(-1*file_count,file_count):
    #     print(xn)
        RGB = cv2.imread(f1)
        n=25
        sum=0
        i=1
        while i            # sum=sum+i
            out.write(RGB)

            i=i+1
        # out.write(RGB)
        # del gray ,xx,f1
        # end_time = datetime.datetime.now()
        # print(end_time)
    # del RGB ,img,framx,width,size,data_path,files,file_count ##indir,oudir,data,
        # del video_out,videoheight,videowidth
    out.release()
 

## Main Function

color_gray(var)
end_time = datetime.datetime.now()
print(end_time)

Sub file:
import numpy as np
import os
import glob

def inout_root(var):
    cwd = os.path.dirname(os.path.abspath(__file__))
   #  var='nb'
    path=cwd+"/"+var+'.txt'
    f = open(path,'r')
    message = f.readline()

    txp=message.split("#")
    dcm_dir=txp
    input_dir=dcm_dir[1]
    output_dir=dcm_dir[3]
    dcm_height=dcm_dir[5]
    dcm_width=dcm_dir[7]
    dcmaxis_dir=dcm_dir[9]
    dcmdecimal_val=dcm_dir[11]
    actaul_center=dcm_dir[13]
    end_value=dcm_dir[15]
    out_videoname=dcm_dir[17]
    # print(input_dir,output_dir,dcm_height,dcm_width)
    data_path = os.path.join(str(input_dir), '*jpg')

    files = glob.glob(data_path)
       # RGB=[]
    files =  glob.glob(data_path)
    file_count = len(files)
   #  print(message)  
    return [input_dir,output_dir,dcm_height,dcm_width,file_count,dcmaxis_dir,dcmdecimal_val,actaul_center,end_value,out_videoname]
# stl_name=stl_name["stl_name"]
# stl_rootname=outdir+"/"+stl_name+'.stl'
# dcm=inout_root('nbx')
# input_dir=dcm[0]
# output_dir=dcm[1]
# videoheight=dcm[2]
# videoheight=int(videoheight)
# videowidth=dcm[3]
# videowidth=int(videowidth)
# dcm_len=dcm[4]
# dcmaxis_dir=dcm[5]
# dcmdecimal_val=dcm[6]
# actual_center=dcm[7]
# actual_center=int(actual_center)
# end_value=dcm[8]
# end_value=int(end_value)
# out_videoname=dcm[9]
# vide_name=output_dir+"/"+out_videoname+'.mp4'
# # print(vide_name)
 print(input_dir,output_dir,videoheight,videowidth,dcm_len,dcmaxis_dir,dcmdecimal_val,actual_center,end_value)
# # print(dcm)

Input Params:
input_dir#/home/hp/Desktop/vscode/WORD2VIDEO/IMAGE#out_dir#/home/hp/Desktop/vscode/WORD2VIDEO#Video_height#3508#Video_widh#2481#direction#y#slidesvalue#0.5#actl_center#2092#end_val#4184#videoname#E-tron-Y-fram#


                                                   Installation Pacakges
1.Python
2.Opencv





























Monday, 25 November 2019

Polygon-Shape-Detection-counting

               Polygon-Shape-Detection-Counting


Input Image: 




Output Images:









                                                                Source Code :
Main code 1 :

import cv2
import numpy as np
import os

im = cv2.imread('input1.jpg')


imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(imgray, 220, 255, 0)
edges = cv2.Canny(thresh,150,180,apertureSize = 3)

ret, labels = cv2.connectedComponents(~thresh)

x=0

[m,n]=np.shape(thresh)


c=1
cwd = os.getcwd()
msk=np.zeros(np.shape(thresh))
while c
    msk=np.zeros(np.shape(thresh))
    msk[(labels==c)]=[255]
    msk=np.array(msk,dtype=np.uint8)
    msk_img=str(c)+'.jpg'
    filename = os.path.join(cwd, msk_img)
    cv2.imwrite(filename,msk)
    c=c+1

print("Total Polygon Objects ", c)



Code 2 :

Main code 2:

import cv2
import numpy as np
import os
im = cv2.imread('input1.jpg')


imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(imgray, 220, 255, 0)
edges = cv2.Canny(thresh,150,180,apertureSize = 3)

ret, labels = cv2.connectedComponents(~thresh)

x=0

[m,n]=np.shape(thresh)


c=1
cwd = os.getcwd()
msk=np.zeros(np.shape(thresh))
while c    msk=np.zeros(np.shape(thresh))
    msk[(labels==c)]=[255]
    msk=np.array(msk,dtype=np.uint8)
    edges = cv2.Canny(msk,150,180,apertureSize = 3)
    image2, contours, _ = cv2.findContours(edges    , cv2.CHAIN_APPROX_NONE, cv2.CHAIN_APPROX_SIMPLE)
    cnt=contours[-1]
    msk_img=str(c)+'.jpg'
    filename = os.path.join(cwd, msk_img)

    ## Objects side detection using controus and defects
    ## Objets sides are mentioned red color marker
    import obj_sid
    # obj_sid.sides(cnt,im)
    obj_sid.equl_side(cnt,im,msk,filename)
    cv2.namedWindow('image contours', cv2.WINDOW_GUI_NORMAL)
    cv2.drawContours(im, contours[-1],-1, (0, 255, 0), 3)
    cv2.imshow('image contours',im)
    cv2.waitKey(0)
    # cv2.imwrite(filename,msk)
    c=c+1
print("Total Polygon Objects ", c)



                                                                 Function code:

import cv2
import numpy as np
import os
im = cv2.imread('input1.jpg')


imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(imgray, 220, 255, 0)
edges = cv2.Canny(thresh,150,180,apertureSize = 3)

ret, labels = cv2.connectedComponents(~thresh)

x=0

[m,n]=np.shape(thresh)


c=1
cwd = os.getcwd()
msk=np.zeros(np.shape(thresh))
while c    msk=np.zeros(np.shape(thresh))
    msk[(labels==c)]=[255]
    msk=np.array(msk,dtype=np.uint8)
    edges = cv2.Canny(msk,150,180,apertureSize = 3)
    image2, contours, _ = cv2.findContours(edges    , cv2.CHAIN_APPROX_NONE,       cv2.CHAIN_APPROX_SIMPLE)
    cnt=contours[-1]
    msk_img=str(c)+'.jpg'
    filename = os.path.join(cwd, msk_img)

    ## Objects side detection using controus and defects
    ## Objets sides are mentioned red color marker
    import obj_sid
    # obj_sid.sides(cnt,im)
    obj_sid.equl_side(cnt,im,msk,filename)
    cv2.namedWindow('image contours', cv2.WINDOW_GUI_NORMAL)
    cv2.drawContours(im, contours[-1],-1, (0, 255, 0), 3)
    cv2.imshow('image contours',im)
    cv2.waitKey(0)

    # cv2.imwrite(filename,msk)
    c=c+1
print("Total Polygon Objects ", c)



                                                   Installation Pacakges
1.Python
2.Opencv















Wednesday, 29 May 2019

SK IMAGE FILTER'S EFFECTS

              SK IMAGE FILTER'S EFFECTS


INPUT IMAGE:


SK FILTERED IMAGE:


                                                   Installation Pacakges
1.Python
2.Opencv

Saturday, 23 February 2019

Automatic mail Generation from MATLAB

                      Automaticmail

Source code:

[mail,password]=mailpass()
setpref('Internet','SMTP_Server','smtp.gmail.com');
setpref('Internet','E_mail',mail);
setpref('Internet','SMTP_Username',mail);
setpref('Internet','SMTP_Password',password);
props = java.lang.System.getProperties;
props.setProperty('mail.smtp.auth','true');
props.setProperty('mail.smtp.socketFactory.class', 'javax.net.ssl.SSLSocketFactory');
props.setProperty('mail.smtp.socketFactory.port','465');
% Send the email.  Note that the first input is the address you are sending the email to
sendmail(mail,'Test from SELVA','Hello! This is a test from SELVA!')

                                                   Software Requirement
1.MATLAB 2014A



Automaticmail

Thursday, 22 November 2018

                   Floor Detection Application

Detect and display the floor using Live Images:

Demo Output:

Input Images Used:



Output Images:

AI Model Segmented Images:



                                        RND using MATLAB Programming

MATLAB Code start here

clc

clear all

close all;

% [a,b]=uigetfile('*.jpg','Segmented    1   image');

rgb=imread('\correct\10r.jpg');

figure,imshow(rgb) 

title('Segmented image')

%  Threshold 

% Pixel 143 71 111 %% in gray 97

gray=rgb2gray(rgb);

figure,imshow(gray) 

title('Segmented grayscale')

hl=gray<97;

hl=find(hl==1);

sz=size(gray)

mask=zeros(sz);

mask(hl)=255;

figure,imshow(mask)

title('binary image')

BW2 = bwareaopen(mask, 2945);

figure,imshow(BW2)

% se = strel('ball',2,5);

% se = strel('disk',2);

% afterOpening = imopen(mask,se);

% se = strel('disk',11);        

% se2 = strel('line',3,90)

se = strel('disk',2);        

se2 = strel('line',3,90)

IM2 = imdilate(BW2,se);

figure,imshow(IM2)

title('smoothed edge')

hls=find(IM2==1);

nohls=find(IM2==0);

edg_img=edge(IM2,'Canny');

figure,imshow(edg_img)

title('coordinate edge')

% [a1,b]=uigetfile('*.jpg','original');

% original=imread('correct\2.jpg');

% figure,imshow(original)

floor_img=imread('\tl2.jpg');

original=rgb;

red_l=original(:,:,1);

green_l=original(:,:,2);

blue_l=original(:,:,3);

red_l(hls)=255;

green_l(hls)=0.22;

blue_l(hls)=0.33;

seg=cat(3,red_l,green_l,blue_l);

figure,imshow(seg)

%% sheet read

% [ax,vx]=uigetfile('*.jpg');

% sheet=imread(ax);

sheet=imread('\tl2.jpg');

sh=size(rgb);

resz=imresize(sheet,sh(1:2));

r_resz=resz(:,:,1);

g_resz=resz(:,:,2);

b_resz=resz(:,:,3);

r_resz(nohls)=0;

g_resz(nohls)=0;

b_resz(nohls)=0;

recn=cat(3,r_resz,g_resz,b_resz);

red_l(hls)=0;

green_l(hls)=0;

blue_l(hls)=0;

figure,imshow(r_resz)

figure,imshow(red_l)

r1=imfuse(red_l,r_resz,'blend','Scaling','joint');

g1=imfuse(green_l,g_resz,'blend','Scaling','joint');

b1=imfuse(blue_l,b_resz,'blend','Scaling','joint');

recon=cat(3,r1,g1,b1);

figure,imshow(recon*2)

imwrite(recon*2,'rechanged8.jpg')

figure,imshow(imfuse(red_l,r_resz,'blend','Scaling','joint'))


                       Application Development using Python

Packages Installation:

1.Python 3.6 

Packages:

pip install opencv-contrib-python=3.4.2.17

pip install pixellib

pip intall numpy

Module run:

Input parameters:

# model_root=r'.hf'  ## model root

# input_imgdir='' ## Input Image root

# output_imgdir= '' ## Segment root

# sheet_image='' ## Floor sheet image root 

# Smoothed_root='' # Final input root

How to use Packages Import ?

import floorgui

import imgmerg

image_segment(model_root,input_imgdir,output_imgdir,sheet_image,Smoothed_root)

How to Run:

Use Test.py-----Testing 

Terminal : python Test.py

Model Download Link:

https://drive.google.com/file/d/1q6dZmlc6_H-B8i-yS_fGsXVQ8lFjy3zw/view?usp=sharing

Source Code Link:


















Sunday, 17 June 2018

Image Layer Splitting

               OpenCV C++ Image Splitting


Source Code:

#include  <opencv2/opencv.hpp>
#include  <opencv2/imgproc/imgproc.hpp>
//#include <opencv2/highgui/highgui.hpp>
#include <iostream>
//#include <iostream>
//#include <opencv2/imgcodecs/imgcodecs.hpp>
//using namespace std;
using namespace cv;
using namespace std;


int main()
{
Mat image;
image=imread("appa.jpg",CV_LOAD_IMAGE_ANYCOLOR);
Mat r, g, b;
r=image;
// splitting
Mat src;
vector<Mat> rgbChannels(3);
split(src,rgbChannels);
Mat fin_img;
g=Mat::zeros(Size(image.cols,image.rows),CV_8UC1);
{

vector<Mat>channels;
channels.push_back(g);
//channels.push_back(g);
//channels.push_back(rgbChannels[2]);
merge(channels,fin_img);
namedWindow("Green",1);
imshow("Green",fin_img);
}
imshow("Image_input",image);
waitKey(0);

//waitKey(0);
destroyAllWindows();



}


                                                   Installation Pacakges
1.Python
2.Opencv

Tuesday, 15 May 2018

Object Segmentation

                 Object Segmentation

Object Segmentation using MATLAB:
Demo Video:

                                                   Software Requirement
MATLAB

Saturday, 3 June 2017

selvakarna


IMAGE CLAHE SK ALGORITHM MATLAB CODE:
%%              ENHANCEMENT PROCESS 
%--------------APPLYING CLAHE ALGORITHM------------------------------------

  

INT_THRSH=0.5; %-----------------------------------------------------------% INTENSITY THRESHOLD VALUE
LOW_LMT=0.008; %-----------------------------------------------------------% PIXEL INTENSITY LOWER LIMIT LEVEL
UP_LMT=0.992; %------------------------------------------------------------% HIGH THRESHOLD VALUE
IMG=FILTR_IM;
[m1 n1]=size(FILTR_IM);
AD=double(FILTR_IM)./255; 
MEAN_AD=INT_THRSH-mean(mean(AD));
AD=AD+MEAN_AD*(1-AD);
IMG=AD.*255;
k=1;
ARRY=sort(reshape(IMG,m1*n1,1));
MIN_VAL(1)=ARRY(ceil(LOW_LMT*m1*n1)); 
MAX_VAL(1)=ARRY(ceil(UP_LMT*m1*n1));
IMG=(IMG-MIN_VAL(1))/(MAX_VAL(1)-MIN_VAL(1));
RECON_IMG=uint8(IMG.*255);
subplot(523);
imshow(RECON_IMG);

title('ENHANCED IMAGE');





C++  Code For Image read 


#include <iostream>

#include <opencv2/core.hpp>

#include <opencv2/imgproc.hpp>

#include <opencv2/imgcodecs.hpp>

#include<opencv2/highgui.hpp>

using namespace std;
using namespace cv;

int main()
{
Mat img;
Mat gry;
img=cv::imread("test.jpg",CV_LOAD_IMAGE_COLOR);

 cv::imshow("image",img);
 char k;
k=cv::waitKey(0);
if(k=='s')
cv::destroyAllWindows();
return 0;
}

Output:
























sk_baby input image

MATLAB code for sk baby read and RGB2GRAY conversion Code 
clc
clear all;
close all;
a=imread('sk.jpg');
imshow(a)
c=rgb2gray(a);
imshow(c)
title('gray image');
sk_baby_bw=im2bw(c,0.54);
figure,imshow(sk_baby_bw);
title('sk_baby_binary_image');



                                                            Sk_baby_Gray Image;


Sk_baby_Binary Image;

FACE EYE MOUTH DETECTION