C語言實現bmp圖像平移操作
平移變換是一種幾何變換。平移的公式為:x1=x0+t,y1=y0+t,其中(x0,y0)是原圖像中的坐標,(x1,y1)是經過平移變換后的對應點的坐標。
在編程中,先將處理后圖像的所有區(qū)域賦值為白色,然后找出平移后顯示區(qū)域的左上角點(x0,y0)和右下角點(x1,y1),分以下幾種情況處理:
先看x方向(width為圖像的寬度)
(1)t<=-width,圖像向左移動,此時圖像完全移除了顯示區(qū)域,所以不做任何處理;
(2)-width<t<=0,圖像向左移動,圖像區(qū)域的x范圍為0~width-|t|,對用于原圖像的范圍為|t|~width;
(3)0<t<width,圖像右移,圖像的x范圍是t~width,對應于原圖的范圍是0~width-t;
(4)t>=width,圖像向右移動且完全移出了顯示區(qū)域,因此不做處理。
上下平移的方法與左右移動相同。
左右平移C語言代碼如下:
// left_right_translation.cpp : 定義控制臺應用程序的入口點。 // #include "stdafx.h" #include<windows.h> #include<stdio.h> #include<math.h> int _tmain(int argc, _TCHAR* argv[]) { int width; int height; RGBQUAD *pTableColor; unsigned char *pBmpBuf1,*pBmpBuf2; BITMAPFILEHEADER bfhead; BITMAPINFOHEADER bihead; //讀出源圖像的信息 FILE *fpr=fopen("E:\\picture\\dog.bmp","rb"); if(fpr==0) return 0; fread(&bfhead,14,1,fpr); fread(&bihead,40,1,fpr); width=bihead.biWidth; height=bihead.biHeight; int LineByte=(width*8/8+3)/4*4; pTableColor=new RGBQUAD[256]; fread(pTableColor,sizeof(RGBQUAD),256,fpr); pBmpBuf1=new unsigned char[LineByte*height]; fread(pBmpBuf1,LineByte*height,1,fpr); fclose(fpr); //將處理后的圖像賦值為白色 pBmpBuf2=new unsigned char[LineByte*height]; for(int i=0;i<height;i++) for(int j=0;j<width;j++) { unsigned char *p; p=(unsigned char*)(pBmpBuf2+LineByte*i+j); (*p)=255; } //左右平移功能的實現 int t; printf("請輸入左平移或右平移的大小t(左移t<0,右移t>0):"); scanf("%d",&t); int k=abs(t); printf("%d",k); if(t<0) { if(t>=(-width)) { for(int i=0;i<height;i++) for(int j=0;j<(width-k);j++) { unsigned char *p1,*p2; p1=pBmpBuf1+LineByte*i+j+k; p2=pBmpBuf2+LineByte*i+j; (*p2)=(*p1); } } } else { if(t<=width) { for(int i=0;i<height;i++) for(int j=k;j<width;j++) { unsigned char *p1,*p2; p1=pBmpBuf1+LineByte*i+j-k; p2=pBmpBuf2+LineByte*i+j; (*p2)=(*p1); } } } //保存處理后的圖像 FILE *fpw=fopen("dog.bmp","wb"); fwrite(&bfhead,14,1,fpw); fwrite(&bihead,40,1,fpw); fwrite(pTableColor,sizeof(RGBQUAD),256,fpw); fwrite(pBmpBuf2,LineByte*height,1,fpw); fclose(fpw); return 0; }
原圖:
向左平移100個像素后圖像:
向右移動200像素:
相關文章
Qt?自定義屬性Q_PROPERTY不顯示float類型的解決
這篇文章主要介紹了Qt?自定義屬性Q_PROPERTY不顯示float類型的問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11