【 Silverlight】Bitmap 位图和Particle引擎


毋庸置疑又是繁忙的一年过去了,在这一年中我的项目BLUR BLUR BLUR以致于我到现在才有时间发表一篇新的BLOG,不过放心,十年不鸣,一鸣惊人。我带给你的总是业界最新的技术

首先也是首要的我们今天要讨论流数据和颗粒,下面是部分的代码:

注意: 上传任何的24位位图所有的二进制流都在客户端处理,所以服务端不需要任何的处理



这里的主循环用来从客户端的对话框中取出一个位图,然后将其解重要信息解析到客户端的一个数组,然后保存那些重要的图像颜色信息

   [...]
   
using System.Windows.Media.Imaging;
   
using System.IO;
   
using System.Windows.Browser;
   
using System.Windows.Resources;

   drawSqaure[] tiles;     
   
double totalCol = 0;
   
double totalRow = 0;
   
double imageWidth = 0;
   
double imageHeight = 0;

   [...]
   
   
private void OpenBMP()
   
{
       OpenFileDialog ofd 
= new OpenFileDialog();

       
if (ofd.ShowDialog() == DialogResult.OK)
       
{
           Stream stream 
= ofd.SelectedFile.OpenRead();
           output 
= ofd.SelectedFile.Name;

        
       
// Find out how big the file is. Create a Byte array to hold it.
       
// Read the values you need from the Bitmap data stream...
    
           
int nBytes = Convert.ToInt32(stream.Length);
           
byte[] ByteArray = new byte[nBytes];
           
int nBytesRead = stream.Read(ByteArray, 0, nBytes);
           stream.Close();

    
       
// BMP Header files start with B and M in Ascii
//
通过文件头的信息来判断文件的类型
                      
           
if ((ByteArray[0== 66&& (ByteArray[1== 77))
           
{
               output 
+= " [24bit BMP File] ";
           }

           
else
           
{
               output 
= " ERROR: File is not a BMP";
               txtOut.Text 
= output;
               
return;
           }

       
       
// BMP files will pad the stream with leading zeros if the
       
// image width in pixels is not divisble by 4
         
           imageWidth 
= (double)(convert4Bytes(ByteArray[18], ByteArray[19], 
            ByteArray[
20], ByteArray[21]));
           
double rowPad = imageWidth % 4;
           imageHeight 
= (double)(convert4Bytes(ByteArray[22], ByteArray[23], 
            ByteArray[
24], ByteArray[25]));
           
int dataOffset = convert4Bytes(ByteArray[10], ByteArray[11], 
            ByteArray[
12], ByteArray[13]);
           
int bitDepth = convert2Bytes(ByteArray[28], ByteArray[29]);
           
int imageDataSize = convert4Bytes(ByteArray[34], ByteArray[35], 
            ByteArray[
36], ByteArray[37]);

           
if ( (imageWidth > 600|| (imageHeight > 600) ) {
               output 
= "ERROR: Image too large. Please select another file.";
               txtOut.Text 
= output;
               
return;
           }


           
if (bitDepth != 24)
           
{
               output 
+= "ERROR: Color depth must be set at 24 bits.";
               txtOut.Text 
= output;
               
return;
           }


       
    
// I will be calculating out the color average of 10x10 pixel 
    
// squares from the image and storing them in a drawSqaure object.
    
// A 24bit BMP uses 3 bytes per pixel for the color. This code 
    
// can easily be expanded to support other bit depths as well.
    
           
int resolution = 10;
           
int bytesPerPixel = 3;

           totalCol 
= Math.Floor( imageWidth / resolution);
           totalRow 
= Math.Floor( imageHeight / resolution);

           
int totalTiles = (int)(totalCol * totalRow);
           tiles 
= new drawSqaure[totalTiles];
                        
           
double rowOffset = 0;
           
double pointer = 0;
           
int index = 0;

       
    
// Here is the important part. I have now stored the Bitmap 
    
// image's stream in my byte array and I have created an array 
    
// of 'drawSquare' objects to be populated with the average
    
// of the 10 x 10 pixel square color values I will next calculate.
       

            
for (int r = 0; r < totalRow; r++)
            
{
        
    
// BMP files send their pixel data from the bottom left corner
    
// of the image UP. Also, while their pixel data is traditional 
    
// 0-255 per RGB color, the ORDER is reversed, so it comes in 
    
// BGR, not RGB.
        
            rowOffset 
= 54 + (r*(resolution * 
            ((imageWidth 
* bytesPerPixel) + rowPad) ));
            
for (int c = 0; c < totalCol; c++)
            
{
            pointer 
= rowOffset + (c * resolution * bytesPerPixel);
            drawSqaure d 
= new drawSqaure();
            
int b = 0;
            
int g = 0;
            
int red = 0;
                        
            
for (int i = 0; i < resolution; i++)
            
{
              
for (int y = 0; y < resolution; y++)
              
{
                 
int calc = Convert.ToInt32(pointer + 
            (i
*((imageWidth*bytesPerPixel)+rowPad)) + (y*3));
                 b 
+= (int)ByteArray[calc];
                 g 
+= (int)ByteArray[calc+1];
                 red 
+= (int )ByteArray[calc + 2];
              }

            }

        
    
// Since the above nested for loops will sample a 10 x 10 pixel   
        
// square, I need to divide the sum of each Color by 100 to 
        
// get its color average per channel.
          
            d.red 
= red / 100;
            d.blue 
= b / 100;
            d.green 
= g / 100;
            tiles[index] 
= d;
            index
++;
          }

      }

      txtOut.Text 
= output;
      ByteArray 
= null;
      buildUI();
    }

}


drawSquare 对象保存的是每个画布TILE将添加到屏幕的颜色的平均值:
    public class drawSqaure
    
{
        
public int red getset; }
        
public int blue getset; }
        
public int green getset; }

    }


下面是一个创建UI的主循环

   private void buildUI()
   
{
     
int index = 0;
     
int nodeSize = 2;
     nodes.Children.Clear();

     
for (int r = 0; r < totalRow; r++)
     
{
       
for (int c = 0; c < totalCol; c++)
        
{
          node n 
= new node();
          n.SetValue(NameProperty, 
"n_" + c.ToString() + "_" + r.ToString());
          n.X 
= origin.X - (totalCol*(nodeSize*.5)) + (c * nodeSize);
          n.Y 
=  origin.Y - 30 + (totalRow*(nodeSize*.5)) - (r * nodeSize);
          n.anchor 
= new Point(n.X, n.Y);
          n.vX 
= 0;
          n.vY 
= 0;
          drawSqaure d 
= tiles[index];
          index
++;
          n.setColor(Color.FromArgb(
0xFF, Convert.ToByte(d.red), 
        Convert.ToByte(d.green), Convert.ToByte(d.blue))); 
          nodes.Children.Add(n);
        }

      }


      index 
= 0;
      tiles 
= null;
   }


        
private Int32 convert4Bytes(byte a, byte b, byte c, byte d) 
    
return ( (d<<24| (c<<16| (b<<8| (a)); }

        
private Int32 convert2Bytes(byte a, byte b)
    
return ((b << 8| (a)); }


用户控制节点是空的,我们可以通过setColor()设置2×2的矩形的颜色,或者通过X,Y属性,正如我前面无数次提到的那样

最后的动画看起来就是这样的:

 
       void sb_Completed(object sender, EventArgs e)
        
{
            
foreach (node n in nodes.Children)
            
{
                n.vX 
+= ((double)r.Next(100- 50.0)/ 5.0;
                n.vY 
+= ((double)r.Next(100- 50.0/ 5.0;
                n.vX 
*= buzz;
                n.vY 
*= buzz;
                n.X 
+= n.vX;
                n.Y 
+= n.vY;
                n.X 
+= (n.anchor.X - n.X) * .07;
                n.Y 
+= (n.anchor.Y - n.Y) * .07;
            }


            sb.Begin();
        }


当然在我的例子里我添加了很多的树枝啊铃铛啊什么的,来控制滚动条中的BUZZ变量的位置扽等,但是上面的俄代码对于要使例子能够跑起来却是必要的







Needless to say, its been one hectic year so far! Between Project Maestro at SXSW, Teaching at MIX08, Winning the PhizzPop nationals, Artists in Residency and getting ready for the Web 2.0 Expo, this is the first chance I've had to push up a new post! But this is a great time for Silverlight development and I'll be keeping you updated with some amazing things just over the horizon!


First things first, we're going to talk about Streaming data and particles today. Here's the project the code snippet comes from:

Instructions: Move the slider to increase the particle buzz. Upload any 24 bit .BMP file. All binary streams are processed client side, there is no server manipulation required.



Here is the main loop that takes the BMP file from a client side dialog box, parses it on the client side to extract the important informatio, and populate an array of custom color objects that will be used to draw the tiles:

   [...]
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows.Browser;
using System.Windows.Resources;

drawSqaure[] tiles;
double totalCol = 0;
double totalRow = 0;
double imageWidth = 0;
double imageHeight = 0;

[...]

private void OpenBMP()
{
OpenFileDialog ofd = new OpenFileDialog();

if (ofd.ShowDialog() == DialogResult.OK)
{
Stream stream = ofd.SelectedFile.OpenRead();
output = ofd.SelectedFile.Name;


// Find out how big the file is. Create a Byte array to hold it.
// Read the values you need from the Bitmap data stream...

int nBytes = Convert.ToInt32(stream.Length);
byte[] ByteArray = new byte[nBytes];
int nBytesRead = stream.Read(ByteArray, 0, nBytes);
stream.Close();


// BMP Header files start with B and M in Ascii

if ((ByteArray[0] == 66) && (ByteArray[1] == 77))
{
output += " [24bit BMP File] ";
}
else
{
output = " ERROR: File is not a BMP";
txtOut.Text = output;
return;
}

// BMP files will pad the stream with leading zeros if the
// image width in pixels is not divisble by 4

imageWidth = (double)(convert4Bytes(ByteArray[18], ByteArray[19],
ByteArray[20], ByteArray[21]));
double rowPad = imageWidth % 4;
imageHeight = (double)(convert4Bytes(ByteArray[22], ByteArray[23],
ByteArray[24], ByteArray[25]));
int dataOffset = convert4Bytes(ByteArray[10], ByteArray[11],
ByteArray[12], ByteArray[13]);
int bitDepth = convert2Bytes(ByteArray[28], ByteArray[29]);
int imageDataSize = convert4Bytes(ByteArray[34], ByteArray[35],
ByteArray[36], ByteArray[37]);

if ( (imageWidth > 600) || (imageHeight > 600) ) {
output = "ERROR: Image too large. Please select another file.";
txtOut.Text = output;
return;
}

if (bitDepth != 24)
{
output += "ERROR: Color depth must be set at 24 bits.";
txtOut.Text = output;
return;
}


// I will be calculating out the color average of 10x10 pixel
// squares from the image and storing them in a drawSqaure object.
// A 24bit BMP uses 3 bytes per pixel for the color. This code
// can easily be expanded to support other bit depths as well.

int resolution = 10;
int bytesPerPixel = 3;

totalCol = Math.Floor( imageWidth / resolution);
totalRow = Math.Floor( imageHeight / resolution);

int totalTiles = (int)(totalCol * totalRow);
tiles = new drawSqaure[totalTiles];

double rowOffset = 0;
double pointer = 0;
int index = 0;


// Here is the important part. I have now stored the Bitmap
// image's stream in my byte array and I have created an array
// of 'drawSquare' objects to be populated with the average
// of the 10 x 10 pixel square color values I will next calculate.


for (int r = 0; r < totalRow; r++)
{

// BMP files send their pixel data from the bottom left corner
// of the image UP. Also, while their pixel data is traditional
// 0-255 per RGB color, the ORDER is reversed, so it comes in
// BGR, not RGB.

rowOffset = 54 + (r*(resolution *
((imageWidth * bytesPerPixel) + rowPad) ));
for (int c = 0; c < totalCol; c++)
{
pointer = rowOffset + (c * resolution * bytesPerPixel);
drawSqaure d = new drawSqaure();
int b = 0;
int g = 0;
int red = 0;

for (int i = 0; i < resolution; i++)
{
for (int y = 0; y < resolution; y++)
{
int calc = Convert.ToInt32(pointer +
(i*((imageWidth*bytesPerPixel)+rowPad)) + (y*3));
b += (int)ByteArray[calc];
g += (int)ByteArray[calc+1];
red += (int )ByteArray[calc + 2];
}
}

// Since the above nested for loops will sample a 10 x 10 pixel
// square, I need to divide the sum of each Color by 100 to
// get its color average per channel.

d.red = red / 100;
d.blue = b / 100;
d.green = g / 100;
tiles[index] = d;
index++;
}
}
txtOut.Text = output;
ByteArray = null;
buildUI();
}
}


The drawSquare object simply holds the averaged color values per canvas tile we will add to the screen:

    public class drawSqaure
{
public int red { get; set; }
public int blue { get; set; }
public int green { get; set; }

}


And here is what the buildUI() loop looks like:

   private void buildUI()
{
int index = 0;
int nodeSize = 2;
nodes.Children.Clear();

for (int r = 0; r < totalRow; r++)
{
for (int c = 0; c < totalCol; c++)
{
node n = new node();
n.SetValue(NameProperty, "n_" + c.ToString() + "_" + r.ToString());
n.X = origin.X - (totalCol*(nodeSize*.5)) + (c * nodeSize);
n.Y = origin.Y - 30 + (totalRow*(nodeSize*.5)) - (r * nodeSize);
n.anchor = new Point(n.X, n.Y);
n.vX = 0;
n.vY = 0;
drawSqaure d = tiles[index];
index++;
n.setColor(Color.FromArgb(0xFF, Convert.ToByte(d.red),
Convert.ToByte(d.green), Convert.ToByte(d.blue)));
nodes.Children.Add(n);
}
}

index = 0;
tiles = null;
}

private Int32 convert4Bytes(byte a, byte b, byte c, byte d)
{ return ( (d<<24) | (c<<16) | (b<<8) | (a)); }

private Int32 convert2Bytes(byte a, byte b)
{ return ((b << 8) | (a)); }



The node user control is empty except for a 2x2 rectangle that we can change the fill with through its setColor() function as well as the X and Y public properties that I've gone over many times before.

Finally, the animation engine looks something like this:

        void sb_Completed(object sender, EventArgs e)
{
foreach (node n in nodes.Children)
{
n.vX += ((double)r.Next(100) - 50.0)/ 5.0;
n.vY += ((double)r.Next(100) - 50.0) / 5.0;
n.vX *= buzz;
n.vY *= buzz;
n.X += n.vX;
n.Y += n.vY;
n.X += (n.anchor.X - n.X) * .07;
n.Y += (n.anchor.Y - n.Y) * .07;
}

sb.Begin();
}
Of course, I added a couple more bells and whistles in mine, such as controlling the value of the buzz variables above by the position of the slider, but I'll leave you to customize your project anyway you want. The above outlines the essentials required to get it up and running.

Hope you like it. Drop me a note if you do anything cool with this...
内容概要:本文介绍了基于SMA-BP黏菌优化算法优化反向传播神经网络(BP)进行多变量回归预测的项目实例。项目旨在通过SMA优化BP神经网络的权重阈值,解决BP神经网络易陷入局部最优、收敛速度慢及参数调优困难等问题。SMA算法模拟黏菌寻找食物的行为,具备优秀的全局搜索能力,能有效提高模型的预测准确性训练效率。项目涵盖了数据预处理、模型设计、算法实现、性能验证等环节,适用于多变量非线性数据的建模预测。; 适合人群:具备一定机器学习基础,特别是对神经网络优化算法有一定了解的研发人员、数据科学家研究人员。; 使用场景及目标:① 提升多变量回归模型的预测准确性,特别是在工业过程控制、金融风险管理等领域;② 加速神经网络训练过程,减少迭代次数训练时间;③ 提高模型的稳定性泛化能力,确保模型在不同数据集上均能保持良好表现;④ 推动智能优化算法与深度学习的融合创新,促进多领域复杂数据分析能力的提升。; 其他说明:项目采用Python实现,包含详细的代码示例注释,便于理解二次开发。模型架构由数据预处理模块、基于SMA优化的BP神经网络训练模块以及模型预测与评估模块组成,各模块接口清晰,便于扩展维护。此外,项目还提供了多种评价指标可视化分析方法,确保实验结果科学可信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值