c#數字圖像處理(八)圖像平移


使圖像沿水平方向和垂直方向移動

        /// <summary>
        /// 圖像平移
        /// </summary>
        private void translation_Click(object sender, EventArgs e)
        {
            if (curBitmap!=null)
            {
                translation traForm = new translation();
                if (traForm.ShowDialog()==DialogResult.OK)
                {
                    Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
                    BitmapData bmpData = curBitmap.LockBits(rect, ImageLockMode.ReadWrite, curBitmap.PixelFormat);
                    IntPtr ptr = bmpData.Scan0;
                    int bytes = bmpData.Stride * bmpData.Height;
                    byte[] grayValues = new byte[bytes];
                    Marshal.Copy(ptr, grayValues, 0, bytes);

                    //得到兩個方向的圖像平移量
                    int x = Convert.ToInt32(traForm.GetXOFFset);
                    int y = Convert.ToInt32(traForm.GetYOffset);

                    byte[] tempArray = new byte[bytes];
                    //臨時初始化為白色(255)像素
                    for (int i = 0; i < bytes; i++)
                    {
                        tempArray[i] = 255;
                    }
                    
                    for (int j = 0; j < curBitmap.Height; j++)
                    {//保證縱向平移不出界
                        if ((j + y) < curBitmap.Height && (j + y) > 0)
                        {
                            for (int i = 0; i < curBitmap.Width * 3; i += 3)
                            {
                                if ((i + x * 3) < curBitmap.Width * 3 && (i + x * 3) > 0)
                                {//保證橫向平移不出界
                                    tempArray[(i + x * 3) + 0 + (j + y) * bmpData.Stride] = grayValues[i + 0 + j * bmpData.Stride];
                                    tempArray[i + x * 3 + 1 + (j + y) * bmpData.Stride] = grayValues[i + 1 + j * bmpData.Stride];
                                    tempArray[i + x * 3 + 2 + (j + y) * bmpData.Stride] = grayValues[i + 2 + j * bmpData.Stride];
                                }
                            }
                        }
                    }


                    //數組復制,返回平移圖像
                    grayValues = (byte[])tempArray.Clone();
                    Marshal.Copy(grayValues, 0, ptr, bytes);
                    curBitmap.UnlockBits(bmpData);
                }
                Invalidate();
            }
        

要注意像素格式PixelFormat,如24位灰度圖像是1440萬色,但是我們書上給的算法是對8為進行處理,可以采用分割的思想將24位拆開成3個8位,由這三個8為所保存的數據組合為24位,在處理的時候就將他們分開處理但是要整體觀看

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM