[問題] opencv 搭配 C 寫影像任意角度旋轉

作者: amateuruser (U文心得大師)   2017-06-15 11:37:01
開發平台(Platform): (Ex: Win10, Linux, ...)
W10
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
Visual studio 2010
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
Opencv ver2.4.9
問題(Question):
無法正確執行結果
餵入的資料(Input):
任意jpg圖片
預期的正確結果(Expected Output):
可以輸入角度
正確輸出旋轉後的圖片
錯誤結果(Wrong Output):
顯示記憶體違規,不知道那裡下手
程式碼(Code):(請善用置底文網頁, 記得排版)
#include " highgui.h"
#include <cv.h>
#include <math.h>
#include <stdio.h>
#include <Windows.h>
using namespace std;
void tran( unsigned char * frame_in, unsigned char * frame_out, int height, int width,int degree)
{
int x1,y1,i,j;
double pi=3.1415926;
double angle=degree*pi/180;
int x,y,z;
for(x=0; x<width; x++)
{
for(y=0;y<height; y++)
{
for(z=0;z<3;z++)
{
x1=i*cos(angle)-j*sin(angle);
y1=j*cos(angle)+i*sin(angle);
if((x1>=0)&&(x1<width)&&(y1>=0)&&(y1<height))
{
frame_out[(y*width+x)*3+z] = frame_in[(x1*width+y1)*3+z];
}else{
frame_out[(y*width+i)*3+z] = 0;
}
}
}
}
}
int main()
{
//
int degree;
printf("choose the degree to rotate the picture\n");
scanf("%d",&degree);
//
IplImage *Image1 ;
Image1=cvLoadImage("lena.jpg",1);
int height, width;
height = Image1->height;
width = Image1->width;
cvNamedWindow("Original Image", CV_WINDOW_AUTOSIZE);
cvShowImage("Original Image",Image1);
unsigned char * frame_in;
unsigned char * frame_out;
frame_in = (unsigned char *)malloc(height*width*3*sizeof(unsigned char));
frame_out = (unsigned char *)malloc(height*width*3*sizeof(unsigned char));
/* Load Image to frame_in */
for(int i=0 ; i<height*width*3 ; i++)
{
frame_in[i] = Image1->imageData[i];
}
tran(frame_in, frame_out, height, width, degree); //轉置
/* 從frame_out存回Image1 */
for(int i=0 ; i<height*width*3 ; i++)
{
Image1->imageData[i] = frame_out[i];
}
cvNamedWindow("Result", CV_WINDOW_AUTOSIZE);
cvShowImage("Result",Image1);
cvWaitKey(0);
free(frame_in);
free(frame_out);
return 0;
}
補充說明(Supplement):
暫時無,有會在下方回覆,謝謝此版
作者: libertyleave (SSLin)   2017-06-15 13:13:00
你 轉置 function 中, i,j 似乎沒有給初始值就拿來用了, 這樣你 x1 y1 的給array用可能會有問題你迴圈是用x,y 看不出來 i j是哪裡來的因為你 tran(...) 裡面有問題呀還有像你有一個 if理面是frame_out[(y*width+x)*3+z] = fram_in[...]到了 else 中是frame_out[(y*width+i)*3+z] = 0x 怎麼會變成 i 了如果你是指 frame_in[i] = Image1->imageData[i]存不進去 你要確定 Image1->imageData[] 的大小有到hight*width*3 呀 話說為甚麼要*3我覺得 Image1->imageData[] 的大小應該只會有長X寬
作者: Zero0910 (みくに最高≧▽≦)   2017-06-15 17:16:00
opencv不是有提供旋轉的函式 還是你是要練習? :p*3是因為RGB吧 雖然應該是這樣寫:(y*width*3+x)+z然後直接用width不太對 因為opecv在配記憶體會幫你align正確應該用(y*image1->widthStep+x)+z (假設為8bit的圖)

Links booklink

Contact Us: admin [ a t ] ucptt.com