コード例 #1
0
        /*updates connectionIO. If yolu do not wish to update some values, input negatives and they will be ignored
         * for connected, 0 is false, 1 is true*/
        public void Update_IO_Displays(int connected, long connections, long sentTelemetry, long recievedCommands, bool newconnection = false)
        {
            if (newconnection)
            {
                Logging.Add("Client N " + connected.ToString() + " connected");
                Logic.Status.LogChanges = Logging.GetFullLog();
            }
            else
            {
            }

            if (UI_Feedback.InvokeRequired)
            {
                UI_Feedback.Invoke(_iofeedback, connected, connections, sentTelemetry, recievedCommands, false);
            }
            else
            {
                if (connected >= 0)
                {
                    UI_DisplayConnectionStatus.Text = connected == 0 ? "No" : "Yes";
                }
                if (connections > 0)
                {
                    UI_DisplayNetworkConnections.Text = connections.ToString();
                }
                if (sentTelemetry > 0)
                {
                    UI_DisplaySentTelemetry.Text = sentTelemetry.ToString();
                }
                if (recievedCommands > 0)
                {
                    UI_DisplayRecievedComms.Text = recievedCommands.ToString();
                }
            }
        }
コード例 #2
0
        private static void Close_Cameras()
        {
            Logging.Add("Closing Cameras");

            foreach (Imaging.CameraBase cam in _cameras)
            {
                cam.Dispose();
            }
        }
コード例 #3
0
        //Works like crap
        public static void WriteThreeChannelsPerChannel(ushort[][][] AllImages, String path, int bitdepth)
        {
            int toreturn = 0;

            using (Tiff tif = Tiff.Open(path, "w"))
            {
                if (tif == null)
                {
                    Logging.Add("couldn't create a tiff file in location " + path);
                    toreturn = 0;
                }
                else
                {
                    int width  = AllImages[0][0].Length;
                    int height = AllImages[0].Length;

                    tif.SetField(TiffTag.IMAGEWIDTH, width);
                    tif.SetField(TiffTag.IMAGELENGTH, height);
                    tif.SetField(TiffTag.BITSPERSAMPLE, bitdepth);
                    tif.SetField(TiffTag.SAMPLESPERPIXEL, 3);
                    tif.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT);
                    tif.SetField(TiffTag.ROWSPERSTRIP, height);
                    tif.SetField(TiffTag.XRESOLUTION, 88.0);
                    tif.SetField(TiffTag.YRESOLUTION, 88.0);
                    tif.SetField(TiffTag.RESOLUTIONUNIT, ResUnit.CENTIMETER);
                    tif.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                    tif.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
                    tif.SetField(TiffTag.COMPRESSION, Compression.NONE);
                    tif.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);
                    ;

                    int bytespersample = (bitdepth / 8);

                    unsafe
                    {
                        //now write to disk
                        for (int i = 0; i < AllImages[0].Length; i++) // iterate height
                        {
                            byte[] buffer = new byte[width * bytespersample * 3];

                            Buffer.BlockCopy(AllImages[0][i], 0, buffer, 0, bytespersample * AllImages[0][i].Length);
                            Buffer.BlockCopy(AllImages[1][i], 0, buffer, bytespersample * AllImages[0][i].Length, bytespersample * AllImages[1][i].Length);
                            if (AllImages.Length >= 3)
                            {
                                Buffer.BlockCopy(AllImages[2][i], 0, buffer, bytespersample * AllImages[0][i].Length * 2, bytespersample * AllImages[1][i].Length);
                            }

                            tif.WriteScanline(buffer, i);
                        }
                    }


                    tif.FlushData();
                    tif.Close();
                }
            }
        }
コード例 #4
0
 public static void Reinitialise()
 {
     if (_TcaptueImage.Status != System.Threading.Tasks.TaskStatus.Running)
     {
         Logging.Add("Reinitialising cameras");
         Close_Cameras();
         Initialise_Cameras();
     }
     else
     {
         Logging.Add("Can't Reinitialise Cameras While Running");
     }
 }
コード例 #5
0
 public static void Initialise_Cameras()
 {
     Logging.Add("initialising cameras");
     _cameras       = new Imaging.CameraBase[Imaging.CameraBase.GetNOfAllCameras()];
     Status.Cameras = (short)_cameras.Length;
     if (_cameras.Length > 0)
     {
         _cameras[0] = new CameraXimea("21402542");
     }
     if (_cameras.Length > 1)
     {
         _cameras[1] = new CameraXimea("09403750");
     }
 }
コード例 #6
0
 private void Resized(object sender, EventArgs e)
 {
     try
     {
         foreach (var scaler in _scalersStructure)
         {
             if (scaler.subject != null)
             {
                 scaler.scaler.Scale(scaler.subject);
                 scaler.subject.Font     = scaler.scaler.get_Font();
                 scaler.subject.Margin   = scaler.scaler.get_Margin();
                 scaler.subject.Padding  = scaler.scaler.get_Padding();
                 scaler.subject.Size     = scaler.scaler.get_Size();
                 scaler.subject.Location = scaler.scaler.get_Location();
             }
         }
     }
     catch (Exception exception)
     {
         Logging.Add(exception.ToString() + exception.Message);
     }
 }
コード例 #7
0
        public async void SendData(TelemetryR data)
        {
            var localSesionId = _sesionID;

            if (NetworkIo == null || !_tcpClient.Connected)
            {
                // _userinterface.Update_IO_Displays(0, _clientsConnected, _sentframes, _commandsRecived);
                //cts.Cancel();
            }
            else
            {//we get  "cannot accees disposed object here, this is an important error
                try
                {
                    if (await NetworkIo.WriteData(data))
                    {
                        _sentframes++;
                        Userinterface.Update_IO_Displays(-1, _clientsConnected, _sentframes, _commandsRecived);
                    }
                    else
                    {
                        Userinterface.Update_feedback("Sending Telemetry Failed");
                        if (_sesionID == localSesionId)
                        {
                            cts.Cancel();
                        }
                    }
                }
                catch (Exception exception)
                {
                    Userinterface.Update_feedback("Sending Telemetry Failed");
                    Logging.Add(exception.ToString() + exception.Message);
                    if (_sesionID == localSesionId)
                    {
                        cts.Cancel();
                    }
                }
            }
        }
コード例 #8
0
        public async void Readnetwork()
        {
            long localSesionId     = _sesionID;
            var  localCancellation = cts;

            if (!AllConnections.Exists(p => p == this)) //if it is not in the list of dysfunctional connections, ad it there
            {
                AllConnections.Add(this);
            }

            try
            {
                _tcpListen = new TcpListener(LocalIp, _port);
                Userinterface.Update_IP_Config(LocalIp, _port);
                _tcpListen.Start();

                Active = true;
                Userinterface.Update_IO_Displays(0, _clientsConnected, _sentframes, _commandsRecived);
                using (_tcpClient = await _tcpListen.AcceptTcpClientAsync())
                {
                    using (NetworkIo = new Nio <Command, TelemetryR>())
                    {
                        NetworkIo.Initiate
                            (_tcpClient.GetStream(), new Command(false, 1, 1), new TelemetryR(), cts);
                        _clientsConnected++;
                        Userinterface.Update_IO_Displays(1, _clientsConnected, _sentframes, _commandsRecived, true);

                        while (!localCancellation.IsCancellationRequested)
                        {
                            try
                            {
                                Command temp = await NetworkIo.RecieveData();

                                _commandsRecived++;
                                Userinterface.Update_IO_Displays(1, _clientsConnected, _sentframes, _commandsRecived);
                                Userinterface.Update_Command(temp);
                            }
                            catch (ArgumentNullException exception)
                            {
                                Logging.Add(exception.ToString() + exception.Message);
                                /* Indicates Disconnection*/
                                if (_sesionID == localSesionId)
                                {
                                    cts.Cancel();
                                }
                                break;
                            }
                            catch (System.IO.IOException exception)
                            {
                                Logging.Add(exception.ToString() + exception.Message);
                                if (_sesionID == localSesionId)
                                {
                                    cts.Cancel();
                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                //_userinterface.Update_feedback("Port is already in use, choosing random port");

                /*Here was a really bad idea with changing ports
                 * var rand = new Random();
                 * _port = (ushort)rand.Next(0, 65000);
                 *
                 *
                 */
                if (exception.Message.Contains("address is not valid "))
                {
                    _connectionErorCount++;
                    if (!DisposedConnections.Exists(p => p == this)) //if it is not in the list of dysfunctional connections, ad it there
                    {
                        DisposedConnections.Add(this);
                    }
                    Active = false;
                    Dispose();
                    Logging.Add("Attempted to start listeninig on invalid IP address " + LocalIp.ToString());
                }
                else if (exception.Message.Contains("Only one usage of each socket address (protocol/network address/port) is normally permitted"))
                {
                    _connectionErorCount++;
                    if (!DisposedConnections.Exists(p => p == this)) //if it is not in the list of dysfunctional connections, ad it there
                    {
                        DisposedConnections.Add(this);
                    }
                    Active = false;
                    Dispose();

                    string listofDisposedconnections = "Disposed COnnections:";

                    string listofAllconnections = "All COnnections:";

                    foreach (Servlet connection in DisposedConnections)
                    {
                        listofDisposedconnections += connection.LocalIp + "\n";
                    }

                    foreach (Servlet connection in AllConnections)
                    {
                        listofAllconnections += connection.LocalIp + "\n";
                    }

                    Logging.Add("Attempted to start listening on " + LocalIp.ToString() + " but socket address is already in use \n" + listofAllconnections + listofDisposedconnections);
                }
                else if (exception.Message.Contains("Cannot access a disposed object"))
                {
                    if (!DisposedConnections.Exists(p => p == this)) //if it is not in the list of dysfunctional connections, ad it there
                    {
                        DisposedConnections.Add(this);
                    }
                    Active = false;
                    Dispose();
                    Logging.Add("Connection " + LocalIp.ToString() + "was closed");
                }
                else
                {
                    Active = false;
                    Logging.Add(exception.ToString() + exception.Message);
                    if (_sesionID == localSesionId)
                    {
                        cts.Cancel();
                    }
                }
            }
        }
コード例 #9
0
        /*Read  The Camera*/

        private static void CaptueImage()
        {
            while (Status.Active && _cameras.Length > 0)
            {
                stopwatchCapture.Reset();
                stopwatchCapture.Start();

                if (Interlocked.CompareExchange(ref _updateDue, 0, 1) == 1)
                //checks if there is an update due, if it is then replaces the _updatedue with 0, and enters the loop
                {
                    //updates camera settings
                    foreach (CameraBase cam in _cameras)
                    {
                        if (cam.GetCurrentState() == CameraBase.State.AquiIdle)
                        //stops aquisition on each camera is they are idle
                        {
                            cam.StopAquisition();
                        }
                        cam.UpdateSettings(Status.Exposureμs, (float)Status.Gain, (float)Status.GammaY,
                                           (float)Status.GammaC);
                    }
                    Status.PertTime[0] = (int)stopwatchCapture.ElapsedMilliseconds;
                    stopwatchCapture.Stop();
                }
                else
                {
                    //calculating sensor driven exposure

                    if (Status.SensorDrivenExposure)
                    {
                        if (Status.Lsensors[0] > 0 && Status.Lsensors[1] > 0)
                        {
                            double brightness = (Status.Lsensors[0] + Status.Lsensors[1]) / 2d;//estimate the brightness by averaging the two sensors
                            //calculate nessesary exposure by dividing coefficient by brightness, multiply by a million to get milliseconds
                            Status.Exposureμs = (int)((Status.SensorResponce / brightness) * 1000000d);
                        }
                        else
                        {
                            Logging.Add("Sensor Driven Exposure set, but Light sensors are not connected");
                        }
                    }


                    //take a picture
                    foreach (CameraBase cam in _cameras)
                    {
                        if (cam.GetCurrentState() == CameraBase.State.OpenIdle)
                        //start aquisition on each camera is they are not in aqusition state
                        {
                            if (Status.SensorDrivenExposure)
                            {
                                cam.DirectlyUpdateSettings(Status.Exposureμs, (float)Status.Gain);
                            }
                            cam.StartAquisition();
                        }
                        /////////////Check for closed cameras and handle it!!!!
                    }
                    ushort[][][] temp = new ushort[_cameras.Length][][];


                    Parallel.For(0, _cameras.Length, i =>
                    {
                        temp[i] = _cameras[i].TakeImageUshort2D(stopwatchCapture);
                    });

                    // CQ.Enqueue(temp); //enque onto a concurrent queue, that serves to pass information to the task
                    bool imagingSucceded = true;

                    foreach (var image in temp)
                    {
                        if (image == null)
                        {
                            imagingSucceded = false;
                        }
                    }

                    if (!imagingSucceded)
                    {
                        //camera failed ot aquire an image, do not procced
                    }
                    else if (Interlocked.Increment(ref _FilesWriting) < 3)
                    {
                        Task _writeToDisk = new Task(() =>
                        {
                            WriteToDisk(temp);
                        });
                        _writeToDisk.Start();
                    }
                    else
                    {
                        //skip writing a file
                    }


                    stopwatchCapture.Stop();
                    int delay = (int)((1000 / Status.FPS) - stopwatchCapture.ElapsedMilliseconds);

                    if (delay > 0)
                    {
                        System.Threading.Thread.Sleep(delay);
                    }
                    else
                    {
                    }
                    Status.PertTime[3] = (int)stopwatchCapture.ElapsedMilliseconds;
                }
            }
        }
コード例 #10
0
        /*setup timers, connections and variables*/
        public UI_NetStatusPanel()
        {
            string errmsg = "";

            InitializeComponent();


            //Setup scalers and controls that must be scaled
            UIsetup();


            _cmdUpdate  = Update_CommandUI;
            _iofeedback = Update_IO_Displays;

            // Setup the API to use local USB devices
            if (YAPI.RegisterHub("usb", ref errmsg) != YAPI.SUCCESS)
            {
                set_display1("error: " + errmsg);
                Logging.Add("Cant initiaet Yocto API, do you have another instance running?");
            }
            else
            {
                Logging.Add("Yapi Initiated");
            }

            //Set Sensors 1 and 2
            sensor1 = YLightSensor.FindLightSensor("L1" + ".lightSensor");
            if (sensor1 == null)
            {
                set_display1("no L1 sensor");
            }
            else
            {
                set_display1("L1 Ok");
            }

            sensor2 = YLightSensor.FindLightSensor("L2" + ".lightSensor");
            if (sensor2 == null)
            {
                set_display2("no L2 sensor"); Logging.Add("L1 not connected");
            }
            else
            {
                set_display2("L2 Ok");
            }

            /*delegates for ui updates*/
            _updatedisplay1 = (set_display1);
            _updatedisplay2 = (set_display2);
            _updatefeedback = (Update_feedback);
            _ipConfig       = Update_IP_Config;

            Logic.Initialise_Cameras();


            Servlet.Userinterface = this; ///assigning treference to ui for the servlets to conduct updates. This needs to be changed!

            Logic.Start();

            //start a timer
            _UsbLightReading = new System.Threading.Timer(Lsensor_Tick, null, 0, 1000);

            //start a timer
            _NetworkTimer = new System.Threading.Timer(Nmanager.Tick, null, 0, 1000);
        }
コード例 #11
0
        /*Is called when a frame is recieved from network. Updates accoring to received settings*/
        public void Update_Command(Command recieved)
        {
            Logging.Add(recieved.LogChanges);

            if (Logic.Status.Active == false && recieved.Active == true)   //triggers if currently cameras are not active, and they are commanded to turn on
            {
                //if user provided no
                if (recieved.Foldername.Length == 0)
                {
                    DateTime folderstamp = DateTime.Now;
                    Logic.CurrentPath = Logic.StaticPath + folderstamp.Hour.ToString() + "." + folderstamp.Minute.ToString() + " on " + folderstamp.Day.ToString() + "." + folderstamp.Month.ToString();
                }
                else
                {
                    Logic.CurrentPath = Logic.StaticPath + recieved.Foldername;
                }


                if (System.IO.Directory.Exists(Logic.CurrentPath))
                {
                    //if folder exists do nothign
                }
                else
                {
                    System.IO.Directory.CreateDirectory(Logic.CurrentPath);
                }

                Logging.Add("Starting imaging, saving to " + Logic.CurrentPath);
                Logic.Status.Active = recieved.Active;
                Logic.Start();
            }
            else if (Logic.Status.Active == false && recieved.Active == false)
            {
            }
            else if (Logic.Status.Active == true && recieved.Active == false)
            {
                Logic.Status.Active = recieved.Active; Logging.Add("Stopping Imaging");
            }
            else if (Logic.Status.Active == true && recieved.Active == true)
            {
            }
            else
            {
                Logging.Add("Status.Imaging or cmd.Imaging is undefined! This is imposible! ");
                throw new Exception("Status.Imaging or cmd.Imaging is undefined! This is imposible! ");
            }

            if (Logic.Status.Gain != recieved.Gain)
            {
                Logging.Add("Gain changed to " + recieved.Gain.ToString());
                Logic.Status.Gain = recieved.Gain;
            }
            else
            {
            }

            //Set exposure, but only if sersor drive exposure is disabled
            Logic.Status.SensorDrivenExposure = recieved.SensorDrivenExposure;
            Logic.Status.SensorResponce       = recieved.SensorResponce;
            if (Logic.Status.SensorDrivenExposure)
            {
                //do nothing, exposure will be set by sensors
            }
            else
            {
                if (Logic.Status.Exposureμs != recieved.Exposureμs)
                {
                    Logging.Add("Exposure changed to " + recieved.Exposureμs.ToString());
                    Logic.Status.Exposureμs = recieved.Exposureμs;
                }
            }

            if (Logic.Status.FPS != recieved.FPS)
            {
                Logging.Add("FPS changed to " + recieved.FPS.ToString());
                Logic.Status.FPS = recieved.FPS;
            }
            else
            {
            }

            if (Logic.Status.curBitDepth != recieved.curBitDepth)
            {
                Logging.Add("curBitDepth changed to " + recieved.curBitDepth.ToString());
                Logic.Status.curBitDepth = recieved.curBitDepth;
            }
            else
            {
            }

            if (Logic.Status.CurImageImageFormat != recieved.CurImageImageFormat)
            {
                Logging.Add("CurImageImageFormat changed to " + recieved.CurImageImageFormat.ToString());
                Logic.Status.CurImageImageFormat = recieved.CurImageImageFormat;
            }

            bool shiftChanged      = false;
            bool correctionUpdated = false;

            for (int i = 0; i < recieved.Xshift.Length; i++)
            {
                if (recieved.Xshift[i] != Logic.Status.Xshift[i] || recieved.Yshift[i] != Logic.Status.Yshift[i])
                {
                    shiftChanged = true;
                }
                if (recieved.ExpCorrection[i] != Logic.Status.ExpCorrection[i] || recieved.DigitCorrection[i] != Logic.Status.DigitCorrection[i])
                {
                    correctionUpdated = true;
                }
            }

            if (shiftChanged)
            {
                Array.Copy(recieved.Xshift, Logic.Status.Xshift, Logic.Status.Xshift.Length);
                Array.Copy(recieved.Yshift, Logic.Status.Yshift, Logic.Status.Yshift.Length);
                Logging.Add("image Shift changed");
                Logic.ChangeShift();
            }
            if (correctionUpdated)
            {
                Array.Copy(recieved.ExpCorrection, Logic.Status.ExpCorrection, Logic.Status.ExpCorrection.Length);
                Array.Copy(recieved.DigitCorrection, Logic.Status.DigitCorrection, Logic.Status.DigitCorrection.Length);
                Logging.Add("Exposure correction changed");
                Logic.ChangeExpCorr();
            }


            if (recieved.Reinitialise)
            {
                Logic.Reinitialise();
            }
            if (recieved.Shutdown)
            {
                Shutdown2();
            }


            UI_DisplayImagging.Invoke(_cmdUpdate, recieved);

            Logic.QueUpdate(); //tells it to update settings before continuing taking imgaes.

            /*if imaging is true, sets time, if imaging is false then sets timeout to infinite, disabling it */
        }
コード例 #12
0
        public static int WriteOnechannel(ushort[] imageData, String path, int width, int height, int bitdepth)
        {
            int toreturn = 0;

            using (Tiff tif = Tiff.Open(path, "w"))
            {
                if (tif == null)
                {
                    Logging.Add("couldn't create a tiff file in location " + path);
                    toreturn = 0;
                }


                tif.SetField(TiffTag.IMAGEWIDTH, width);
                tif.SetField(TiffTag.IMAGELENGTH, height);
                tif.SetField(TiffTag.BITSPERSAMPLE, bitdepth);
                tif.SetField(TiffTag.SAMPLESPERPIXEL, 1);
                tif.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT);
                tif.SetField(TiffTag.ROWSPERSTRIP, height);
                tif.SetField(TiffTag.XRESOLUTION, 88.0);
                tif.SetField(TiffTag.YRESOLUTION, 88.0);
                tif.SetField(TiffTag.RESOLUTIONUNIT, ResUnit.CENTIMETER);
                tif.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                tif.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
                tif.SetField(TiffTag.COMPRESSION, Compression.NONE);
                tif.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);

                int bytespersample = (bitdepth / 8);



                if (bytespersample == 2)
                {
                    for (int i = 0; i < height; i++)
                    {
                        byte[] buffer = new byte[width * bytespersample]; //allocate a buffer, two bytes per short
                        Buffer.BlockCopy(imageData, width * i * bytespersample, buffer, 0, buffer.Length);
                        tif.WriteScanline(buffer, i);
                    }
                }
                else if (bytespersample == 1)
                {
                    for (int i = 0; i < height; i++)
                    {
                        byte[] buffer = new byte[width * bytespersample];                   //allocate a buffer, one byte per short

                        for (int n = 0; n < width; n++)                                     //iterate through every short
                        {
                            buffer[n] = BitConverter.GetBytes(imageData[width * i + n])[1]; //
                            //assigns the bit in the buffer as a higher byte of short
                        }

                        tif.WriteScanline(buffer, i);
                        i++;
                    }
                }
                else
                {
                    Logging.Add("In saving, bitdepth should be 8 or 16, and it is " + bitdepth);
                }
                tif.FlushData();
                tif.Close();
                toreturn = 1;
            }

            return(toreturn);
        }
コード例 #13
0
        public static void WriteThreeChannelsInterleaved(ushort[][][] AllImages, String path, int bitdepth)
        {
            int toreturn = 0;

            using (Tiff tif = Tiff.Open(path, "w"))
            {
                if (tif == null)
                {
                    Logging.Add("couldn't create a tiff file in location " + path);
                    toreturn = 0;
                }
                else
                {
                    int width  = AllImages[0][0].Length;
                    int height = AllImages[0].Length;

                    tif.SetField(TiffTag.IMAGEWIDTH, width);
                    tif.SetField(TiffTag.IMAGELENGTH, height);
                    tif.SetField(TiffTag.BITSPERSAMPLE, bitdepth);
                    tif.SetField(TiffTag.SAMPLESPERPIXEL, 3);
                    tif.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT);
                    tif.SetField(TiffTag.ROWSPERSTRIP, height);
                    tif.SetField(TiffTag.XRESOLUTION, 88.0);
                    tif.SetField(TiffTag.YRESOLUTION, 88.0);
                    tif.SetField(TiffTag.RESOLUTIONUNIT, ResUnit.CENTIMETER);
                    tif.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                    tif.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
                    tif.SetField(TiffTag.COMPRESSION, Compression.NONE);
                    tif.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);
                    ;

                    int bytespersample = (bitdepth / 8);



                    //now write to disk
                    for (int i = 0; i < AllImages[0].Length; i++)     // iterate height
                    {
                        byte[] buffer = new byte[width * bytespersample * 3];

                        for (int x = 0; x < AllImages[0][i].Length; x++)     //Iterate Width
                        {
                            int offsetLine = x * bytespersample * 3;

                            for (int c = 0; c < AllImages.Length; c++)
                            {
                                int offsetCamera = c * bytespersample;

                                int offsetTotal = offsetCamera + offsetLine;


                                if (bitdepth == 16)
                                {
                                    buffer[offsetTotal]     = BitConverter.GetBytes(AllImages[c][i][x])[0];
                                    buffer[offsetTotal + 1] = BitConverter.GetBytes(AllImages[c][i][x])[1];
                                }
                                else
                                {
                                    buffer[offsetTotal] = BitConverter.GetBytes(AllImages[c][i][x])[1];
                                }
                            }
                        }


                        tif.WriteScanline(buffer, i);
                    }



                    tif.FlushData();
                    tif.Close();
                }
            }
        }
コード例 #14
0
        public static int WriteOnechannel(ushort[][] imageData, String path, int width, int height, int bitdepth)
        {
            int toreturn = 0;

            using (Tiff tif = Tiff.Open(path, "w"))
            {
                if (tif == null)
                {
                    Logging.Add("couldn't create a tiff file in location " + path);
                    toreturn = 0;
                }
                else
                {
                    tif.SetField(TiffTag.IMAGEWIDTH, width);
                    tif.SetField(TiffTag.IMAGELENGTH, height);
                    tif.SetField(TiffTag.BITSPERSAMPLE, bitdepth);
                    tif.SetField(TiffTag.SAMPLESPERPIXEL, 1);
                    tif.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT);
                    tif.SetField(TiffTag.ROWSPERSTRIP, height);
                    tif.SetField(TiffTag.XRESOLUTION, 88.0);
                    tif.SetField(TiffTag.YRESOLUTION, 88.0);
                    tif.SetField(TiffTag.RESOLUTIONUNIT, ResUnit.CENTIMETER);
                    tif.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                    tif.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
                    tif.SetField(TiffTag.COMPRESSION, Compression.NONE);
                    tif.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);

                    int bytespersample = (bitdepth / 8);



                    int i = 0;
                    if (bytespersample == 2)
                    {
                        foreach (ushort[] stripe in imageData)
                        {
                            byte[] buffer = new byte[width * bytespersample]; //allocate a buffer

                            Buffer.BlockCopy(stripe, 0, buffer, 0, stripe.Length * sizeof(short));
                            //block copy copies the bits directly,
                            //so the shorts get atuomatically sptil into bytes without a performance penalty
                            tif.WriteScanline(buffer, i);
                            i++;
                        }
                    }
                    else if (bytespersample == 1)
                    {
                        foreach (ushort[] stripe in imageData)
                        {
                            byte[] buffer = new byte[width * bytespersample]; //allocate a buffer

                            int n = 0;

                            foreach (ushort Pixel in stripe)
                            {
                                buffer[n] = BitConverter.GetBytes(Pixel)[1];
                                //assigns the bit in the buffer as a higher byte of short
                                n++;
                            }

                            tif.WriteScanline(buffer, i);
                            i++;
                        }
                    }
                    else
                    {
                        Logging.Add("In saving, bitdepth should be 8 or 16, and it is " + bitdepth);
                    }
                    tif.FlushData();
                    tif.Close();
                    toreturn = 1;
                }
            }

            return(toreturn);
        }