圖像銳化、梯度、對比度 C++

    ~~~~最近碰到一些需求,居然要改圖像,但是按照要求改了,弄完最後又要求改回去,記錄一下使用過的函數

銳化,梯度增強,對比度

//銳化
void sharpen(unsigned char *pucImage, int iWidth, int iHeight){
	if(pucImage == NULL) return;
	unsigned char *puc = pucImage;
	//申請空間
	unsigned char *puc1 = new unsigned char[iWidth * iHeight];
	int line = 0, value = 0;
	//循環
	for(int i = 1; i < iHeight - 1; i++){
		line = i * iWidth;
		for (int j = 1; j < iWidth - 1; ++j) {
			//銳化
			value = puc[line + j] + (puc[line + j] * 4 - (puc[line - iWidth + j] + puc[line + iWidth + j] + puc[line + 1 + j] + puc[line - 1 + j])) * 2;
			value = value < 0 ? 0 : value;
			value = value > 255 ? 255 : value;
			puc1[line + j] = value;
		}
	}
	//將結果複製回去
	memcpy(pucImage, puc1, iWidth * iHeight* sizeof(unsigned char));
	//刪除空間
	delete[] puc1;
}
//梯度增強
void grad(unsigned char *pucImage, int iWidth, int iHeight){
    if(pucImage == NULL) return;
    unsigned char *puc = pucImage;
    int line = 0, value = 0;
	//申請空間
	unsigned char *puc1 = new unsigned char[iWidth * iHeight];

	//先複製一次
//	memcpy(puc1, pucImage, iWidth * iHeight * sizeof(unsigned char));
	memset(puc1, 128, iWidth * iHeight * sizeof(unsigned char));

    //循環
    for(int i = 1; i < iHeight - 1; i++){
        line = i * iWidth;
        for (int j = 1; j < iWidth - 1; ++j) {
            //銳化
			value = puc[line + j] + static_cast<unsigned char>(0xff & (abs((int)puc[line + j + 1] - puc[line + j]) + abs((int)puc[line + iWidth + j] - puc[line + j])));
			value = value < 0 ? 0 : value;
			value = value > 255 ? 255 : value;
			puc1[line + j] = value;
        }
    }
	//將結果複製回去
	memcpy(pucImage, puc1, iWidth * iHeight* sizeof(unsigned char));
	//刪除空間
	delete[] puc1;
}

#define CHECKVALUE(a) (a & ~0xff) == 0 ? a : a > 255 ? 255 : 0
//對比度
void contrast(unsigned char *pucImage, int iWidth, int iHeight, int contrast_value, unsigned char threshold){
    if(pucImage == NULL) return;
    if (contrast_value == 0)
        return;
    unsigned char *puc = pucImage;
    int line = 0, value = 0;

    double contrast_t = contrast_value <= -255? -1.0f : contrast_value / 255.0f;
    if (contrast_value > 0 && contrast_value < 255)
        contrast_t = 1.0f / (1.0f - contrast_t) - 1.0f;

	unsigned char values[256];
    for(int i = 0; i < 256; i++){
        value =contrast_value > 0 ? CHECKVALUE(i + 1) : i;
        value = contrast_value >= 255 ? (value >= threshold ? 255 : 0) : CHECKVALUE(value + (int)((value - threshold) * contrast_t + 0.5f));
        values[i] = (unsigned char)(contrast_value <= 0 ? CHECKVALUE(value + 1) : value);
    }

    //循環
    for(int i = 1; i < iHeight - 1; i++){
        line = i * iWidth;
        for (int j = 1; j < iWidth - 1; ++j) {
			puc[line + j] = values[puc[line + j]];
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章