I'm using OpenCV to do Canny Edge Detection on images obtained by a camera over LAN. This works, but I keep getting Corrupt JPEG data: premature end of data segment errors at run time once every few frames when I imshow("recv", canny), but I don't get that if I do imshow("recv", frame)

// Block until receive message from a client
do {
    recvMsgSize = sock.recvFrom(buffer, BUF_LEN, sourceAddress, sourcePort);
} while (recvMsgSize > sizeof(int));
int total_pack = ((int*)buffer)[0];

char* longbuf = new char[double(PACK_SIZE * total_pack)];
for (int i = 0; i < total_pack; i++) {
    recvMsgSize = sock.recvFrom(buffer, BUF_LEN, sourceAddress, sourcePort);
         if (recvMsgSize != PACK_SIZE) {
    memcpy(&longbuf[i * PACK_SIZE], buffer, PACK_SIZE);

Mat rawData = Mat(1, PACK_SIZE * total_pack, CV_8UC1, longbuf);
Mat frame = imdecode(rawData, IMREAD_COLOR);
if (frame.size().width == 0) {
Mat canny = CannyThreshold(frame);
imshow("recv", canny);
delete[] longbuf;

1 Answers

Yunus Temurlenk On

if you can get "frame" in mat form, then probably there is something wrong about this line:

Mat canny = CannyThreshold(frame);

Maybe you can change this line with something like this:

int minCannyThreshold = 190;
int maxCannyThreshold = 230;
Canny(frame, frame, minCannyThreshold, maxCannyThreshold, 5, true);
imshow("recv", frame);